diff --git a/pack/acp/opt/coc.nvim/.github/FUNDING.yml b/pack/acp/opt/coc.nvim/.github/FUNDING.yml new file mode 100644 index 0000000..bc74b9d --- /dev/null +++ b/pack/acp/opt/coc.nvim/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +open_collective: cocnvim +patreon: chemzqm diff --git a/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md b/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..3b0eaeb --- /dev/null +++ b/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,45 @@ +--- +name: Bug report +about: Create a report to help us improve +--- + + + +## Result from CocInfo + + + +## Describe the bug + +A clear and concise description of what the bug is. + +## Reproduce the bug + +**We will close your issue when you don't provide minimal vimrc and we can't +reproduce it** + +- Create file `mini.vim` with: + + ```vim + set nocompatible + set runtimepath^=/path/to/coc.nvim + filetype plugin indent on + syntax on + set hidden + ``` + +- Start (neo)vim with command: `vim -u mini.vim` + +- Operate vim. + +## Screenshots (optional) + +If applicable, add screenshots to help explain your problem. diff --git a/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md b/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..066b2d9 --- /dev/null +++ b/pack/acp/opt/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/pack/acp/opt/coc.nvim/.github/workflows/ci.yml b/pack/acp/opt/coc.nvim/.github/workflows/ci.yml new file mode 100644 index 0000000..8be307c --- /dev/null +++ b/pack/acp/opt/coc.nvim/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: coc.nvim CI + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + node-version: [10, 14] + + env: + NODE_ENV: test + + steps: + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install yarn + run: | + curl --compressed -o- -L https://yarnpkg.com/install.sh | bash + - uses: actions/checkout@v2 + - name: yarn install + run: | + yarn global add typescript + yarn + - name: yarn lint + run: yarn lint + - if: matrix.os == 'macos-latest' + name: yarn test on macOS + run: | + curl -LO https://github.com/neovim/neovim/releases/download/nightly/nvim-macos.tar.gz + tar xzf nvim-macos.tar.gz + export PATH="${PATH}:node_modules/.bin:$(pwd)/nvim-osx64/bin" + nvim --version + yarn test + - if: matrix.os == 'ubuntu-latest' + name: yarn test on Ubuntu + run: | + curl -LO https://github.com/neovim/neovim/releases/download/nightly/nvim-linux64.tar.gz + tar xzf nvim-linux64.tar.gz + export PATH="${PATH}:node_modules/.bin:$(pwd)/nvim-linux64/bin" + nvim --version + yarn test + env: + NODE_ENV: test diff --git a/pack/acp/opt/coc.nvim/.gitignore b/pack/acp/opt/coc.nvim/.gitignore index a151978..f9ec5e3 100644 --- a/pack/acp/opt/coc.nvim/.gitignore +++ b/pack/acp/opt/coc.nvim/.gitignore @@ -10,3 +10,4 @@ doc/tags doc/tags-cn node_modules src/__tests__/tags +typings diff --git a/pack/acp/opt/coc.nvim/Readme.md b/pack/acp/opt/coc.nvim/Readme.md index 3b53dd7..4d4037e 100644 --- a/pack/acp/opt/coc.nvim/Readme.md +++ b/pack/acp/opt/coc.nvim/Readme.md @@ -39,7 +39,7 @@ For [vim-plug](https://github.com/junegunn/vim-plug) users: Plug 'neoclide/coc.nvim', {'branch': 'release'} " Or build from source code by using yarn: https://yarnpkg.com -Plug 'neoclide/coc.nvim', {'do': 'yarn install --frozen-lockfile'} +Plug 'neoclide/coc.nvim', {'branch': 'master', 'do': 'yarn install --frozen-lockfile'} ``` in your `.vimrc` or `init.vim`, then restart Vim and run `:PlugInstall`. @@ -91,6 +91,10 @@ possible to avoid conflict with your other plugins. `:verbose imap ` to make sure that your keymap has taken effect. ```vim +" Set internal encoding of vim, not needed on neovim, since coc.nvim using some +" unicode characters in the file autoload/float.vim +set encoding=utf-8 + " TextEdit might fail if hidden is not set. set hidden @@ -207,11 +211,14 @@ xmap ac (coc-classobj-a) omap ac (coc-classobj-a) " Remap and for scroll float windows/popups. -" Note coc#float#scroll works on neovim >= 0.4.3 or vim >= 8.2.0750 -nnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" -nnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" -inoremap coc#float#has_scroll() ? "\=coc#float#scroll(1)\" : "\" -inoremap coc#float#has_scroll() ? "\=coc#float#scroll(0)\" : "\" +if has('nvim-0.4.0') || has('patch-8.2.0750') + nnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" + nnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" + inoremap coc#float#has_scroll() ? "\=coc#float#scroll(1)\" : "\" + inoremap coc#float#has_scroll() ? "\=coc#float#scroll(0)\" : "\" + vnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" + vnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" +endif " Use CTRL-S for selections ranges. " Requires 'textDocument/selectionRange' support of language server. @@ -276,7 +283,24 @@ Try these steps when you have problem with coc.nvim. - If something is not working, [create an issue](https://github.com/neoclide/coc.nvim/issues/new). - +## Backers + +[Become a backer](https://opencollective.com/cocnvim#backer) and get your image on our README on Github with a link to your site. + + + + + + + + + + + + + + + ## License diff --git a/pack/acp/opt/coc.nvim/autoload/coc.vim b/pack/acp/opt/coc.nvim/autoload/coc.vim index 2e2f45f..d7a8832 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc.vim @@ -1,7 +1,6 @@ let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []} let g:coc_user_config = get(g:, 'coc_user_config', {}) let g:coc_global_extensions = get(g:, 'coc_global_extensions', []) -let g:coc_cygqwin_path_prefixes = get(g:, 'coc_cygqwin_path_prefixes', {}) let g:coc_selected_text = '' let g:coc_vim_commands = [] let s:watched_keys = [] @@ -36,14 +35,7 @@ function! coc#refresh() abort endfunction function! coc#on_enter() - if !coc#rpc#ready() - return '' - endif - if s:is_vim - call coc#rpc#notify('CocAutocmd', ['Enter', bufnr('%')]) - else - call coc#rpc#request('CocAutocmd', ['Enter', bufnr('%')]) - endif + call coc#rpc#notify('CocAutocmd', ['Enter', bufnr('%')]) return '' endfunction @@ -102,9 +94,10 @@ endfunction function! coc#_cancel() " hack for close pum - if pumvisible() && &paste != 1 + if pumvisible() let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []} call feedkeys("\CocRefresh", 'i') + call coc#rpc#notify('stopCompletion', []) endif endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/api.vim b/pack/acp/opt/coc.nvim/autoload/coc/api.vim index 47bf03d..43b350a 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/api.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/api.vim @@ -2,11 +2,11 @@ " Description: Client api used by vim8 " Author: Qiming Zhao " Licence: MIT licence -" Last Modified: June 28, 2019 +" Last Modified: Nov 11, 2020 " ============================================================================ if has('nvim') | finish | endif let s:funcs = {} -let s:prop_id = 1000 +let s:prop_offset = get(g:, 'coc_text_prop_offset', 1000) let s:namespace_id = 1 let s:namespace_cache = {} @@ -121,7 +121,7 @@ function! s:funcs.get_api_info() endfunction function! s:funcs.list_bufs() - return map(getbufinfo({'buflisted': 1}), 'v:val["bufnr"]') + return map(getbufinfo({'bufloaded': 1}), 'v:val["bufnr"]') endfunction function! s:funcs.feedkeys(keys, mode, escape_csi) @@ -240,18 +240,13 @@ function! s:funcs.buf_get_mark(bufnr, name) endfunction function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEnd) abort - if !has('textprop') + if !has('textprop') || !has('patch-8.1.1719') return endif let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr - let key = 'Coc'.a:hlGroup.(a:srcId != -1 ? a:srcId : '') - if empty(prop_type_get(key, {'bufnr': a:bufnr})) - call prop_type_add(key, {'highlight': a:hlGroup, 'combine': 1, 'bufnr': a:bufnr}) - if a:srcId != -1 - let cached = getbufvar(bufnr, 'prop_namespace_'.a:srcId, []) - call add(cached, key) - call setbufvar(bufnr, 'prop_namespace_'.a:srcId, cached) - endif + let type = 'CocHighlight'.a:hlGroup + if empty(prop_type_get(type)) + call prop_type_add(type, {'highlight': a:hlGroup, 'combine': 1}) endif let total = strlen(getbufline(bufnr, a:line + 1)[0]) let end = a:colEnd @@ -263,33 +258,44 @@ function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEn if end <= a:colStart return endif - let id = s:prop_id - let s:prop_id = id + 1 + let srcId = a:srcId + if srcId == 0 + while v:true + let srcId = srcId + 1 + if empty(prop_find({'id': s:prop_offset + srcId, 'lnum' : 1})) + break + endif + endwhile + " generate srcId + endif + let id = srcId == -1 ? 0 : s:prop_offset + srcId try - call prop_add(a:line + 1, a:colStart + 1, {'length': end - a:colStart, 'bufnr': bufnr, 'type': key, 'id': id}) + call prop_add(a:line + 1, a:colStart + 1, {'length': end - a:colStart, 'bufnr': bufnr, 'type': type, 'id': id}) catch /^Vim\%((\a\+)\)\=:E967/ " ignore 967 endtry + let g:i = srcId + if a:srcId == 0 + " return generated srcId + return srcId + endif endfunction function! s:funcs.buf_clear_namespace(bufnr, srcId, startLine, endLine) abort - if !has('textprop') + if !has('textprop') || !has('patch-8.1.1719') return endif + let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr + let start = a:startLine + 1 + let end = a:endLine == -1 ? len(getbufline(bufnr, 1, '$')) : a:endLine + 1 if a:srcId == -1 - if a:endLine == -1 - call prop_clear(a:startLine + 1, {'bufnr': a:bufnr}) - else - call prop_clear(a:startLine + 1, a:endLine + 1, {'bufnr': a:bufnr}) - endif + call prop_clear(start, end, {'bufnr' : bufnr}) else - let cached = getbufvar(a:bufnr, 'prop_namespace_'.a:srcId, []) - if empty(cached) - return - endif - for key in cached - call prop_remove({'type': key, 'bufnr': a:bufnr, 'all': 1}) - endfor + try + call prop_remove({'bufnr': bufnr, 'all': 1, 'id': s:prop_offset + a:srcId}, start, end) + catch /^Vim\%((\a\+)\)\=:E968/ + " ignore 968 + endtry endif endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/client.vim b/pack/acp/opt/coc.nvim/autoload/coc/client.vim index 3b945aa..e337435 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/client.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/client.vim @@ -72,25 +72,36 @@ function! s:start() dict let self['running'] = 1 let self['channel'] = job_getchannel(job) else - let original = { - \ 'NODE_NO_WARNINGS': getenv('NODE_NO_WARNINGS'), - \ 'COC_CHANNEL_TIMEOUT': getenv('COC_CHANNEL_TIMEOUT'), - \ 'COC_NO_WARNINGS': getenv('COC_NO_WARNINGS'), - \ 'TMPDIR': getenv('TMPDIR'), - \ } + let original = {'tmpdir': $TMPDIR} " env option not work on neovim - call setenv('NODE_NO_WARNINGS', '1') - call setenv('COC_CHANNEL_TIMEOUT', timeout) - call setenv('COC_NO_WARNINGS', disable_warning) - call setenv('TMPDIR', tmpdir) + if exists('*setenv') + let original = { + \ 'NODE_NO_WARNINGS': getenv('NODE_NO_WARNINGS'), + \ 'COC_CHANNEL_TIMEOUT': getenv('COC_CHANNEL_TIMEOUT'), + \ 'COC_NO_WARNINGS': getenv('COC_NO_WARNINGS'), + \ 'TMPDIR': getenv('TMPDIR'), + \ } + call setenv('NODE_NO_WARNINGS', '1') + call setenv('COC_CHANNEL_TIMEOUT', timeout) + call setenv('COC_NO_WARNINGS', disable_warning) + call setenv('TMPDIR', tmpdir) + else + let $NODE_NO_WARNINGS = 1 + let $COC_NO_WARNINGS = disable_warning + let $TMPDIR = tmpdir + endif let chan_id = jobstart(self.command, { \ 'rpc': 1, \ 'on_stderr': {channel, msgs -> s:on_stderr(self.name, msgs)}, \ 'on_exit': {channel, code -> s:on_exit(self.name, code)}, \}) - for key in keys(original) - call setenv(key, original[key]) - endfor + if exists('*setenv') + for key in keys(original) + call setenv(key, original[key]) + endfor + else + let $TMPDIR = original['tmpdir'] + endif if chan_id <= 0 echohl Error | echom 'Failed to start '.self.name.' service' | echohl None return @@ -120,6 +131,10 @@ function! s:on_exit(name, code) abort let client['channel'] = v:null let client['async_req_id'] = 1 if a:code != 0 && a:code != 143 + " could be syntax error + if a:code == 1 + call s:check_node() + endif echohl Error | echom 'client '.a:name. ' abnormal exit with: '.a:code | echohl None endif endfunction @@ -311,3 +326,14 @@ function! coc#client#open_log() endif execute 'vs '.s:logfile endfunction + +function! s:check_node() abort + let node = get(g:, 'coc_node_path', $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH) + let output = trim(system(node . ' --version')) + let ms = matchlist(output, 'v\(\d\+\).\(\d\+\).\(\d\+\)') + if empty(ms) || str2nr(ms[1]) < 10 || (str2nr(ms[1]) == 10 && str2nr(ms[2]) < 12) + echohl Error + echon '[coc.nvim] Node version '.output.' < 10.12.0, please upgrade node.js or use g:coc_node_path variable.' + echohl None + endif +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/color.vim b/pack/acp/opt/coc.nvim/autoload/coc/color.vim new file mode 100644 index 0000000..d6b04cf --- /dev/null +++ b/pack/acp/opt/coc.nvim/autoload/coc/color.vim @@ -0,0 +1,191 @@ +" Returns an approximate grey index for the given grey level +fun! s:grey_number(x) + if &t_Co == 88 + if a:x < 23 + return 0 + elseif a:x < 69 + return 1 + elseif a:x < 103 + return 2 + elseif a:x < 127 + return 3 + elseif a:x < 150 + return 4 + elseif a:x < 173 + return 5 + elseif a:x < 196 + return 6 + elseif a:x < 219 + return 7 + elseif a:x < 243 + return 8 + else + return 9 + endif + else + if a:x < 14 + return 0 + else + let l:n = (a:x - 8) / 10 + let l:m = (a:x - 8) % 10 + if l:m < 5 + return l:n + else + return l:n + 1 + endif + endif + endif +endfun + +" Returns the actual grey level represented by the grey index +fun! s:grey_level(n) + if &t_Co == 88 + if a:n == 0 + return 0 + elseif a:n == 1 + return 46 + elseif a:n == 2 + return 92 + elseif a:n == 3 + return 115 + elseif a:n == 4 + return 139 + elseif a:n == 5 + return 162 + elseif a:n == 6 + return 185 + elseif a:n == 7 + return 208 + elseif a:n == 8 + return 231 + else + return 255 + endif + else + if a:n == 0 + return 0 + else + return 8 + (a:n * 10) + endif + endif +endfun + +" Returns the palette index for the given grey index +fun! s:grey_colour(n) + if &t_Co == 88 + if a:n == 0 + return 16 + elseif a:n == 9 + return 79 + else + return 79 + a:n + endif + else + if a:n == 0 + return 16 + elseif a:n == 25 + return 231 + else + return 231 + a:n + endif + endif +endfun + +" Returns an approximate colour index for the given colour level +fun! s:rgb_number(x) + if &t_Co == 88 + if a:x < 69 + return 0 + elseif a:x < 172 + return 1 + elseif a:x < 230 + return 2 + else + return 3 + endif + else + if a:x < 75 + return 0 + else + let l:n = (a:x - 55) / 40 + let l:m = (a:x - 55) % 40 + if l:m < 20 + return l:n + else + return l:n + 1 + endif + endif + endif +endfun + +" Returns the palette index for the given R/G/B colour indices +fun! s:rgb_colour(x, y, z) + if &t_Co == 88 + return 16 + (a:x * 16) + (a:y * 4) + a:z + else + return 16 + (a:x * 36) + (a:y * 6) + a:z + endif +endfun + +" Returns the actual colour level for the given colour index +fun! s:rgb_level(n) + if &t_Co == 88 + if a:n == 0 + return 0 + elseif a:n == 1 + return 139 + elseif a:n == 2 + return 205 + else + return 255 + endif + else + if a:n == 0 + return 0 + else + return 55 + (a:n * 40) + endif + endif +endfun + +" Returns the palette index to approximate the given R/G/B colour levels +fun! s:colour(r, g, b) + " Get the closest grey + let l:gx = s:grey_number(a:r) + let l:gy = s:grey_number(a:g) + let l:gz = s:grey_number(a:b) + + " Get the closest colour + let l:x = s:rgb_number(a:r) + let l:y = s:rgb_number(a:g) + let l:z = s:rgb_number(a:b) + + if l:gx == l:gy && l:gy == l:gz + " There are two possibilities + let l:dgr = s:grey_level(l:gx) - a:r + let l:dgg = s:grey_level(l:gy) - a:g + let l:dgb = s:grey_level(l:gz) - a:b + let l:dgrey = (l:dgr * l:dgr) + (l:dgg * l:dgg) + (l:dgb * l:dgb) + let l:dr = s:rgb_level(l:gx) - a:r + let l:dg = s:rgb_level(l:gy) - a:g + let l:db = s:rgb_level(l:gz) - a:b + let l:drgb = (l:dr * l:dr) + (l:dg * l:dg) + (l:db * l:db) + if l:dgrey < l:drgb + " Use the grey + return s:grey_colour(l:gx) + else + " Use the colour + return s:rgb_colour(l:x, l:y, l:z) + endif + else + " Only one possibility + return s:rgb_colour(l:x, l:y, l:z) + endif +endfun + +function! coc#color#rgb2term(rgb) + let l:r = ("0x" . strpart(a:rgb, 0, 2)) + 0 + let l:g = ("0x" . strpart(a:rgb, 2, 2)) + 0 + let l:b = ("0x" . strpart(a:rgb, 4, 2)) + 0 + return s:colour(l:r, l:g, l:b) +endfun diff --git a/pack/acp/opt/coc.nvim/autoload/coc/compat.vim b/pack/acp/opt/coc.nvim/autoload/coc/compat.vim new file mode 100644 index 0000000..824f3dc --- /dev/null +++ b/pack/acp/opt/coc.nvim/autoload/coc/compat.vim @@ -0,0 +1,133 @@ +let s:is_vim = !has('nvim') + +" first window id for bufnr +" builtin bufwinid returns window of current tab only +function! coc#compat#buf_win_id(bufnr) abort + let info = filter(getwininfo(), 'v:val["bufnr"] =='.a:bufnr) + if empty(info) + return -1 + endif + return info[0]['winid'] +endfunction + +function! coc#compat#win_is_valid(winid) abort + if exists('*nvim_win_is_valid') + return nvim_win_is_valid(a:winid) + endif + return !empty(getwininfo(a:winid)) +endfunction + +" clear matches by window id, not throw on none exists window. +" may not work on vim < 8.1.1084 & neovim < 0.4.0 +function! coc#compat#clear_matches(winid) abort + if !coc#compat#win_is_valid(a:winid) + return + endif + let curr = win_getid() + if curr == a:winid + call clearmatches() + return + endif + if s:is_vim + if has('patch-8.1.1084') + call clearmatches(a:winid) + endif + else + if exists('*nvim_set_current_win') + noa call nvim_set_current_win(a:winid) + call clearmatches() + noa call nvim_set_current_win(curr) + endif + endif +endfunction + +function! coc#compat#matchaddpos(group, pos, priority, winid) abort + let curr = win_getid() + if curr == a:winid + call matchaddpos(a:group, a:pos, a:priority, -1) + else + if s:is_vim + if has('patch-8.1.0218') + call matchaddpos(a:group, a:pos, a:priority, -1, {'window': a:winid}) + endif + else + if has('nvim-0.4.0') + call matchaddpos(a:group, a:pos, a:priority, -1, {'window': a:winid}) + elseif exists('*nvim_set_current_win') + noa call nvim_set_current_win(a:winid) + call matchaddpos(a:group, a:pos, a:priority, -1) + noa call nvim_set_current_win(curr) + endif + endif + endif +endfunction + +" hlGroup, pos, priority +function! coc#compat#matchaddgroups(winid, groups) abort + " add by winid + if s:is_vim && has('patch-8.1.0218') || has('nvim-0.4.0') + for group in a:groups + call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1, {'window': a:winid}) + endfor + endif + let curr = win_getid() + if curr == a:winid + for group in a:groups + call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1) + endfor + elseif exists('*nvim_set_current_win') + noa call nvim_set_current_win(a:winid) + for group in a:groups + call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1) + endfor + noa call nvim_set_current_win(curr) + endif +endfunction + +" remove keymap for specfic buffer +function! coc#compat#buf_del_keymap(bufnr, mode, lhs) abort + if !bufloaded(a:bufnr) + return + endif + if exists('*nvim_buf_del_keymap') + try + call nvim_buf_del_keymap(a:bufnr, a:mode, a:lhs) + catch /^Vim\%((\a\+)\)\=:E5555/ + " ignore keymap not exists. + endtry + return + endif + if bufnr == a:bufnr + execute 'silent! '.a:mode.'unmap '.a:lhs + return + endif + if exists('*win_execute') + let winid = coc#compat#buf_win_id(a:bufnr) + if winid != -1 + call win_execute(winid, 'silent! '.a:mode.'unmap '.a:lhs) + endif + endif +endfunction + +" execute command or list of commands in window +function! coc#compat#execute(winid, command) abort + if s:is_vim + if !exists('*win_execute') + throw 'win_execute function not exists, please upgrade your vim.' + endif + if type(a:command) == v:t_string + keepalt call win_execute(a:winid, a:command) + elseif type(a:command) == v:t_list + keepalt call win_execute(a:winid, join(a:command, "\n")) + endif + else + let curr = nvim_get_current_win() + noa keepalt call nvim_set_current_win(a:winid) + if type(a:command) == v:t_string + exec a:command + elseif type(a:command) == v:t_list + exec join(a:command, "\n") + endif + noa keepalt call nvim_set_current_win(curr) + endif +endfunc diff --git a/pack/acp/opt/coc.nvim/autoload/coc/float.vim b/pack/acp/opt/coc.nvim/autoload/coc/float.vim index bb66324..45a6f73 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/float.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/float.vim @@ -1,9 +1,12 @@ " Related to float window create let s:is_vim = !has('nvim') -let s:borderchars = get(g:, 'coc_borderchars', - \ ['─', '│', '─', '│', '┌', '┐', '┘', '└']) +let s:root = expand(':h:h:h') +let s:progresschars = get(g:, 'coc_progress_chars', ['░', '▇']) +let s:borderchars = get(g:, 'coc_borderchars', ['─', '│', '─', '│', '┌', '┐', '┘', '└']) +let s:borderjoinchars = get(g:, 'coc_border_joinchars', ['┬', '┤', '┴', '├']) let s:prompt_win_width = get(g:, 'coc_prompt_win_width', 32) -let s:scrollbar_ns = exists('*nvim_create_namespace') ? nvim_create_namespace('coc-scrollbar') : 0 +let s:prompt_win_bufnr = 0 +let s:float_supported = exists('*nvim_open_win') || has('patch-8.1.1719') " winvar: border array of numbers, button boolean " detect if there's float window/popup created by coc.nvim @@ -44,52 +47,37 @@ function! coc#float#jump() abort endif endfunction -function! coc#float#get_float_mode(lines, config) abort - let allowSelection = get(a:config, 'allowSelection', 0) - let pumAlignTop = get(a:config, 'pumAlignTop', 0) - let mode = mode() - let checked = (mode == 's' && allowSelection) || index(['i', 'n', 'ic'], mode) != -1 - if !checked - return v:null - endif - if !s:is_vim && mode ==# 'i' - " helps to fix undo issue, don't know why. - call feedkeys("\u", 'n') - endif - let dimension = coc#float#get_config_cursor(a:lines, a:config) - if empty(dimension) - return v:null - endif - if pumvisible() && ((pumAlignTop && dimension['row'] <0)|| (!pumAlignTop && dimension['row'] > 0)) - return v:null - endif - return [mode, bufnr('%'), [line('.'), col('.')], dimension] -endfunction - -" create/reuse float window for config position, config including: -" - line: line count relative to cursor, nagetive number means abover cursor. -" - col: column count relative to cursor, nagetive number means left of cursor. +" create or config float window, returns [winid, bufnr], config including: +" - relative: could be 'editor' 'cursor' +" - row: line count relative to editor/cursor, nagetive number means abover cursor. +" - col: column count relative to editor/cursor, nagetive number means left of cursor. " - width: content width without border and title. " - height: content height without border and title. +" - lines: (optional) lines to insert, default to v:null. " - title: (optional) title. " - border: (optional) border as number list, like [1, 1, 1 ,1]. " - cursorline: (optional) enable cursorline when is 1. " - autohide: (optional) window should be closed on CursorMoved when is 1. +" - highlight: (optional) highlight of window, default to 'CocFloating' +" - borderhighlight: (optional) should be array for border highlights, +" highlight all borders with first value. +" - close: (optional) show close button when is 1. +" - buttons: (optional) array of button text for create buttons at bottom. function! coc#float#create_float_win(winid, bufnr, config) abort - call coc#float#close_auto_hide_wins(a:winid) + let lines = get(a:config, 'lines', v:null) + let bufnr = coc#float#create_buf(a:bufnr, lines, 'hide') " use exists if a:winid && coc#float#valid(a:winid) if s:is_vim let [line, col] = s:popup_position(a:config) - call popup_move(a:winid, { + let opts = { + \ 'firstline': 1, \ 'line': line, \ 'col': col, \ 'minwidth': a:config['width'], \ 'minheight': a:config['height'], \ 'maxwidth': a:config['width'], \ 'maxheight': a:config['height'], - \ }) - let opts = { \ 'cursorline': get(a:config, 'cursorline', 0), \ 'title': get(a:config, 'title', ''), \ } @@ -97,29 +85,31 @@ function! coc#float#create_float_win(winid, bufnr, config) abort let opts['border'] = a:config['border'] endif call popup_setoptions(a:winid, opts) + call coc#float#vim_buttons(a:winid, a:config) return [a:winid, winbufnr(a:winid)] else let config = s:convert_config_nvim(a:config) - " not reuse related windows - call coc#float#nvim_close_related(a:winid) + call nvim_win_set_buf(a:winid, bufnr) call nvim_win_set_config(a:winid, config) + call nvim_win_set_cursor(a:winid, [1, 0]) call coc#float#nvim_create_related(a:winid, config, a:config) - return [a:winid, winbufnr(a:winid)] + return [a:winid, bufnr] endif endif let winid = 0 if s:is_vim let [line, col] = s:popup_position(a:config) - let bufnr = coc#float#create_float_buf(a:bufnr) let title = get(a:config, 'title', '') + let buttons = get(a:config, 'buttons', []) + let hlgroup = get(a:config, 'highlight', 'CocFloating') let opts = { \ 'title': title, \ 'line': line, \ 'col': col, + \ 'fixed': 1, \ 'padding': empty(title) ? [0, 1, 0, 1] : [0, 0, 0, 0], \ 'borderchars': s:borderchars, - \ 'highlight': 'CocFloating', - \ 'fixed': 1, + \ 'highlight': hlgroup, \ 'cursorline': get(a:config, 'cursorline', 0), \ 'minwidth': a:config['width'], \ 'minheight': a:config['height'], @@ -129,6 +119,9 @@ function! coc#float#create_float_win(winid, bufnr, config) abort if get(a:config, 'close', 0) let opts['close'] = 'button' endif + if !empty(get(a:config, 'borderhighlight', [])) + let opts['borderhighlight'] = map(a:config['borderhighlight'], 'coc#highlight#compose_hlgroup(v:val,"'.hlgroup.'")') + endif if !s:empty_border(get(a:config, 'border', [])) let opts['border'] = a:config['border'] endif @@ -136,96 +129,104 @@ function! coc#float#create_float_win(winid, bufnr, config) abort if winid == 0 return [] endif + call coc#float#vim_buttons(winid, a:config) if has("patch-8.1.2281") call setwinvar(winid, '&showbreak', 'NONE') endif else let config = s:convert_config_nvim(a:config) - let bufnr = coc#float#create_float_buf(a:bufnr) let winid = nvim_open_win(bufnr, 0, config) if winid == 0 return [] endif - call setwinvar(winid, '&winhl', 'Normal:CocFloating,NormalNC:CocFloating,FoldColumn:CocFloating,CursorLine:CocMenuSel') + let hlgroup = get(a:config, 'highlight', 'CocFloating') + call setwinvar(winid, '&winhl', 'Normal:'.hlgroup.',NormalNC:'.hlgroup.',FoldColumn:'.hlgroup) call setwinvar(winid, '&signcolumn', 'no') + " cursorline highlight not work on old neovim + call setwinvar(winid, '&cursorline', 0) + call setwinvar(winid, 'border', get(a:config, 'border', [])) " no left border if s:empty_border(get(a:config, 'border', [])) || a:config['border'][3] == 0 call setwinvar(winid, '&foldcolumn', 1) endif + call nvim_win_set_cursor(winid, [1, 0]) call coc#float#nvim_create_related(winid, config, a:config) endif - if !s:is_vim - " change cursorline option affects vim's own highlight - call setwinvar(winid, '&cursorline', get(a:config, 'cursorline', 0)) - call setwinvar(winid, 'border', get(a:config, 'border', [])) - endif if get(a:config, 'autohide', 0) call setwinvar(winid, 'autohide', 1) endif if s:is_vim || has('nvim-0.5.0') call setwinvar(winid, '&scrolloff', 0) endif + call setwinvar(winid, 'float', 1) call setwinvar(winid, '&list', 0) call setwinvar(winid, '&number', 0) call setwinvar(winid, '&relativenumber', 0) call setwinvar(winid, '&cursorcolumn', 0) call setwinvar(winid, '&colorcolumn', 0) - call setwinvar(winid, 'float', 1) call setwinvar(winid, '&wrap', 1) call setwinvar(winid, '&linebreak', 1) call setwinvar(winid, '&conceallevel', 2) let g:coc_last_float_win = winid call coc#util#do_autocmd('CocOpenFloat') - return [winid, winbufnr(winid)] + return [winid, bufnr] endfunction function! coc#float#valid(winid) abort - if a:winid == 0 || type(a:winid) != 0 + if a:winid <= 0 return 0 endif - if s:is_vim - return s:popup_visible(a:winid) + if has('nvim') + return nvim_win_is_valid(a:winid) ? 1 : 0 endif - if exists('*nvim_win_is_valid') && nvim_win_is_valid(a:winid) - let config = nvim_win_get_config(a:winid) - return !empty(get(config, 'relative', '')) - endif - return 0 + return s:popup_visible(a:winid) endfunction -" create buffer for popup/float window -function! coc#float#create_float_buf(bufnr) abort - " reuse buffer cause error on vim8 - if a:bufnr && bufloaded(a:bufnr) - return a:bufnr +function! coc#float#nvim_create_related(winid, config, opts) abort + let related = getwinvar(a:winid, 'related', []) + let exists = !empty(related) + let border = get(a:opts, 'border', []) + let highlights = get(a:opts, 'borderhighlight', []) + let hlgroup = get(a:opts, 'highlight', 'CocFloating') + let borderhighlight = type(highlights) == 1 ? highlights : get(highlights, 0, 'CocFloating') + let borderhighlight = coc#highlight#compose_hlgroup(borderhighlight, hlgroup) + let title = get(a:opts, 'title', '') + let buttons = get(a:opts, 'buttons', []) + let pad = empty(border) || get(border, 1, 0) == 0 + if get(a:opts, 'close', 0) + call coc#float#nvim_close_btn(a:config, a:winid, border, borderhighlight, related) + elseif exists + call coc#float#close_related(a:winid, 'close') endif - if s:is_vim - noa let bufnr = bufadd('') - noa call bufload(bufnr) - else - noa let bufnr = nvim_create_buf(v:false, v:true) + if !empty(buttons) + call coc#float#nvim_buttons(a:config, a:winid, buttons, get(border, 2, 0), pad, hlgroup, borderhighlight, related) + elseif exists + call coc#float#close_related(a:winid, 'buttons') endif - " Don't use popup filetype, it would crash on reuse! - call setbufvar(bufnr, '&buftype', 'nofile') - call setbufvar(bufnr, '&bufhidden', 'hide') - call setbufvar(bufnr, '&swapfile', 0) - call setbufvar(bufnr, '&tabstop', 2) - call setbufvar(bufnr, '&undolevels', -1) - return bufnr + if !s:empty_border(border) + call coc#float#nvim_border_win(a:config, a:winid, border, title, !empty(buttons), borderhighlight, related) + elseif exists + call coc#float#close_related(a:winid, 'border') + endif + " Check right border + if pad + call coc#float#nvim_right_pad(a:config, a:winid, hlgroup, related) + elseif exists + call coc#float#close_related(a:winid, 'pad') + endif + call setwinvar(a:winid, 'related', filter(related, 'nvim_win_is_valid(v:val)')) endfunction " border window for neovim, content config with border -function! coc#float#nvim_border_win(config, border, title, related) abort - if s:empty_border(a:border) - return - endif - " width height col row relative - noa let bufnr = nvim_create_buf(v:false, v:true) - call setbufvar(bufnr, '&bufhidden', 'wipe') +function! coc#float#nvim_border_win(config, winid, border, title, hasbtn, hlgroup, related) abort + let winid = coc#float#get_related(a:winid, 'border') let row = a:border[0] ? a:config['row'] - 1 : a:config['row'] let col = a:border[3] ? a:config['col'] - 1 : a:config['col'] let width = a:config['width'] + a:border[1] + a:border[3] - let height = a:config['height'] + a:border[0] + a:border[2] + let height = a:config['height'] + a:border[0] + a:border[2] + (a:hasbtn ? 2 : 0) + let lines = coc#float#create_border_lines(a:border, a:title, a:config['width'], a:config['height'], a:hasbtn) + let bufnr = winid ? winbufnr(winid) : 0 + let bufnr = coc#float#create_buf(bufnr, lines) let opt = { \ 'relative': a:config['relative'], \ 'width': width, @@ -235,17 +236,192 @@ function! coc#float#nvim_border_win(config, border, title, related) abort \ 'focusable': v:false, \ 'style': 'minimal', \ } - let winid = nvim_open_win(bufnr, 0, opt) - if !winid - return + if winid + call nvim_win_set_config(winid, opt) + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) + else + let winid = nvim_open_win(bufnr, 0, opt) + if winid + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) + call setwinvar(winid, 'target_winid', a:winid) + call setwinvar(winid, 'kind', 'border') + call add(a:related, winid) + endif endif - call setwinvar(winid, '&winhl', 'Normal:CocFloating,NormalNC:CocFloating') - let lines = coc#float#create_border_lines(a:border, a:title, a:config['width'], a:config['height']) - call nvim_buf_set_lines(bufnr, 0, -1, v:false, lines) - call add(a:related, winid) endfunction -function! coc#float#create_border_lines(border, title, width, height) abort +" neovim only +function! coc#float#nvim_close_btn(config, winid, border, hlgroup, related) abort + let winid = coc#float#get_related(a:winid, 'close') + let config = { + \ 'relative': a:config['relative'], + \ 'width': 1, + \ 'height': 1, + \ 'row': get(a:border, 0, 0) ? a:config['row'] - 1 : a:config['row'], + \ 'col': a:config['col'] + a:config['width'], + \ 'focusable': v:true, + \ 'style': 'minimal', + \ } + if winid + call nvim_win_set_config(winid, config) + else + let bufnr = coc#float#create_buf(0, ['X']) + let winid = nvim_open_win(bufnr, 0, config) + if winid + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) + call setwinvar(winid, 'target_winid', a:winid) + call setwinvar(winid, 'kind', 'close') + call add(a:related, winid) + endif + call s:nvim_create_keymap(winid) + endif +endfunction + +" Create padding window by config of current window & border config +function! coc#float#nvim_right_pad(config, winid, hlgroup, related) abort + let winid = coc#float#get_related(a:winid, 'pad') + let config = { + \ 'relative': a:config['relative'], + \ 'width': 1, + \ 'height': a:config['height'], + \ 'row': a:config['row'], + \ 'col': a:config['col'] + a:config['width'], + \ 'focusable': v:false, + \ 'style': 'minimal', + \ } + if winid + noa call nvim_win_close(winid, 1) + endif + let bufnr = coc#float#create_buf(0, repeat([''], a:config['height'])) + let winid = nvim_open_win(bufnr, 0, config) + if winid + " neovim'bug: the content shown in window could be wired. + call setwinvar(winid, '&foldcolumn', 1) + call setwinvar(winid, '&winhl', 'FoldColumn:'.a:hlgroup) + call setwinvar(winid, 'target_winid', a:winid) + call setwinvar(winid, 'kind', 'pad') + call add(a:related, winid) + endif +endfunction + +" draw buttons window for window with config +function! coc#float#nvim_buttons(config, winid, buttons, borderbottom, pad, hlgroup, borderhighlight, related) abort + let winid = coc#float#get_related(a:winid, 'buttons') + let width = a:config['width'] + (a:pad ? 1 : 0) + let config = { + \ 'row': a:config['row'] + a:config['height'], + \ 'col': a:config['col'], + \ 'width': width, + \ 'height': 2 + (a:borderbottom ? 1 : 0), + \ 'relative': a:config['relative'], + \ 'focusable': 1, + \ 'style': 'minimal', + \ } + if winid + let bufnr = winbufnr(winid) + call s:create_btns_buffer(bufnr, width, a:buttons, a:borderbottom) + call nvim_win_set_config(winid, config) + else + let bufnr = s:create_btns_buffer(0, width, a:buttons, a:borderbottom) + let winid = nvim_open_win(bufnr, 0, config) + if winid + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) + call setwinvar(winid, 'target_winid', a:winid) + call setwinvar(winid, 'kind', 'buttons') + call add(a:related, winid) + call s:nvim_create_keymap(winid) + endif + endif + if bufnr && a:hlgroup != a:borderhighlight + call nvim_buf_clear_namespace(bufnr, -1, 0, -1) + call nvim_buf_add_highlight(bufnr, 1, a:borderhighlight, 0, 0, -1) + if a:borderbottom + call nvim_buf_add_highlight(bufnr, 1, a:borderhighlight, 2, 0, -1) + endif + let vcols = getbufvar(bufnr, 'vcols', []) + " TODO need change vol to col + for col in vcols + call nvim_buf_add_highlight(bufnr, 1, a:borderhighlight, 1, col, col + 3) + endfor + endif +endfunction + +" Create or refresh scrollbar for winid +" Need called on create, config, buffer change, scrolled +function! coc#float#nvim_scrollbar(winid) abort + if !has('nvim-0.4.0') || !coc#float#valid(a:winid) || getwinvar(a:winid, 'target_winid', 0) + return + endif + let config = nvim_win_get_config(a:winid) + let [row, column] = nvim_win_get_position(a:winid) + let width = nvim_win_get_width(a:winid) + let height = nvim_win_get_height(a:winid) + let bufnr = winbufnr(a:winid) + let cw = getwinvar(a:winid, '&foldcolumn', 0) ? width - 1 : width + let ch = coc#float#content_height(bufnr, cw, getwinvar(a:winid, '&wrap')) + let closewin = coc#float#get_related(a:winid, 'close') + let border = getwinvar(a:winid, 'border', []) + let move_down = closewin && !get(border, 0, 0) + if move_down + let height = height - 1 + endif + let id = coc#float#get_related(a:winid, 'scrollbar') + if ch <= height || height <= 0 + " no scrollbar, remove exists + if id + call s:close_win(id) + endif + return + endif + call coc#float#close_related(a:winid, 'pad') + let sbuf = id ? winbufnr(id) : 0 + let sbuf = coc#float#create_buf(sbuf, repeat([' '], height)) + let opts = { + \ 'row': move_down ? row + 1 : row, + \ 'col': column + width, + \ 'relative': 'editor', + \ 'width': 1, + \ 'height': height, + \ 'focusable': v:false, + \ 'style': 'minimal', + \ } + if id + call nvim_win_set_config(id, opts) + else + let id = nvim_open_win(sbuf, 0 , opts) + if id == 0 + return + endif + call setwinvar(id, 'kind', 'scrollbar') + call setwinvar(id, 'target_winid', a:winid) + endif + let thumb_height = max([1, float2nr(floor(height * (height + 0.0)/ch))]) + let wininfo = getwininfo(a:winid)[0] + let start = 0 + if wininfo['topline'] != 1 + " needed for correct getwininfo + let firstline = wininfo['topline'] + let lastline = s:nvim_get_botline(firstline, height, cw, bufnr) + let linecount = nvim_buf_line_count(winbufnr(a:winid)) + if lastline >= linecount + let start = height - thumb_height + else + let start = max([1, float2nr(round((height - thumb_height + 0.0)*(firstline - 1.0)/(ch - height)))]) + endif + endif + " add highlights + call nvim_buf_clear_namespace(sbuf, -1, 0, -1) + for idx in range(0, height - 1) + if idx >= start && idx < start + thumb_height + call nvim_buf_add_highlight(sbuf, -1, 'PmenuThumb', idx, 0, 1) + else + call nvim_buf_add_highlight(sbuf, -1, 'PmenuSbar', idx, 0, 1) + endif + endfor + call s:add_related(id, a:winid) +endfunction + +function! coc#float#create_border_lines(border, title, width, height, hasbtn) abort let list = [] if a:border[0] let top = (a:border[3] ? s:borderchars[4]: '') @@ -259,7 +435,12 @@ function! coc#float#create_border_lines(border, title, width, height) abort let mid = (a:border[3] ? s:borderchars[3]: '') \.repeat(' ', a:width) \.(a:border[1] ? s:borderchars[1] : '') - call extend(list, repeat([mid], a:height)) + call extend(list, repeat([mid], a:height + (a:hasbtn ? 2 : 0))) + if a:hasbtn + let list[len(list) - 2] = (a:border[3] ? s:borderjoinchars[3]: '') + \.repeat(' ', a:width) + \.(a:border[1] ? s:borderjoinchars[1] : '') + endif if a:border[2] let bot = (a:border[3] ? s:borderchars[7]: '') \.repeat(s:borderchars[2], a:width) @@ -269,43 +450,109 @@ function! coc#float#create_border_lines(border, title, width, height) abort return list endfunction -" Create float window for input -function! coc#float#create_prompt_win(title, default) abort +" Get config, convert lines, create window, add highlights +function! coc#float#create_cursor_float(winid, bufnr, lines, config) abort + if !s:float_supported + return v:null + endif + if s:is_blocking() + return v:null + endif + let pumAlignTop = get(a:config, 'pumAlignTop', 0) + let modes = get(a:config, 'modes', ['n', 'i', 'ic', 's']) + let mode = mode() + let currbuf = bufnr('%') + let pos = [line('.'), col('.')] + if index(modes, mode) == -1 + return v:null + endif + if has('nvim') && mode ==# 'i' + " helps to fix undo issue, don't know why. + call feedkeys("\u", 'n') + endif + let dimension = coc#float#get_config_cursor(a:lines, a:config) + if empty(dimension) + return v:null + endif + if pumvisible() && ((pumAlignTop && dimension['row'] <0)|| (!pumAlignTop && dimension['row'] > 0)) + return v:null + endif + let width = dimension['width'] + let lines = map(a:lines, {_, s -> s =~# '^—' ? repeat('—', width) : s}) + let config = extend({'lines': lines, 'relative': 'cursor'}, a:config) + let config = extend(config, dimension) + call coc#float#close_auto_hide_wins(a:winid) + let res = coc#float#create_float_win(a:winid, a:bufnr, config) + if empty(res) + return v:null + endif + let winid = res[0] + let bufnr = res[1] + call coc#highlight#add_highlights(winid, get(a:config, 'codes', []), get(a:config, 'highlights', [])) + redraw + if has('nvim') + call coc#float#nvim_scrollbar(winid) + endif + return [currbuf, pos, winid, bufnr] +endfunction + +" Create float window for input, neovim only since vim doesn't support focus +function! coc#float#create_prompt_win(title, default, opts) abort call coc#float#close_auto_hide_wins() - noa let bufnr = nvim_create_buf(v:false, v:true) - call nvim_buf_set_lines(bufnr, 0, -1, v:false, [a:default]) - call setbufvar(bufnr, '&bufhidden', 'wipe') " Calculate col let curr = win_screenpos(winnr())[1] + wincol() - 2 - let width = min([max([strdisplaywidth(a:title) + 2, s:prompt_win_width]), &columns - 2]) + let width = coc#helper#min(max([strdisplaywidth(a:title) + 2, s:prompt_win_width]), &columns - 2) if width == &columns - 2 let col = 0 - curr else let col = curr + width <= &columns - 2 ? 0 : &columns - s:prompt_win_width endif - let config = { + let [lineIdx, colIdx] = coc#util#cursor_pos() + let bufnr = 0 + if has('nvim') + let bufnr = s:prompt_win_bufnr + else + execute 'hi link CocPopupTerminal '.get(a:opts, 'highlight', 'CocFloating') + let node = expand(get(g:, 'coc_node_path', 'node')) + let bufnr = term_start([node, s:root . '/bin/prompt.js', a:default], { + \ 'term_highlight': 'CocPopupTerminal', + \ 'hidden': 1, + \ 'term_finish': 'close' + \ }) + call term_setapi(bufnr, "Coc") + endif + let res = coc#float#create_float_win(0, bufnr, { \ 'relative': 'cursor', + \ 'row': lineIdx == 0 ? 1 : 0, + \ 'col': colIdx == 0 ? 0 : col - 1, \ 'width': width, \ 'height': 1, - \ 'row': 0, - \ 'col': col, \ 'style': 'minimal', - \ } - let winid = nvim_open_win(bufnr, 0, config) - if winid == 0 - return [] + \ 'border': [1,1,1,1], + \ 'prompt': 1, + \ 'title': a:title, + \ 'lines': [a:default], + \ 'highlight': get(a:opts, 'highlight', 'CocFloating'), + \ 'borderhighlight': [get(a:opts, 'borderhighlight', 'CocFloating')], + \ }) + if empty(res) || res[0] == 0 + return + endif + let winid = res[0] + let bufnr = res[1] + if has('nvim') + let s:prompt_win_bufnr = res[1] + execute 'sign unplace 6 buffer='.s:prompt_win_bufnr + call nvim_set_current_win(winid) + inoremap + inoremap pumvisible() ? "\" : "\" + exe 'inoremap =coc#float#close_i('.winid.')' + exe 'nnoremap :call coc#float#close('.winid.')' + exe 'inoremap "\=coc#float#prompt_insert(getline(''.''))\\"' + call feedkeys('A', 'in') + else + call setbufvar(bufnr, '&termwinkey', '') endif - call setwinvar(winid, '&winhl', 'Normal:CocFloating,NormalNC:CocFloating') - let related = [] - call coc#float#nvim_border_win(config, [1,1,1,1], a:title, related) - call setwinvar(winid, 'related', related) - call win_gotoid(winid) - inoremap - inoremap pumvisible() ? "\" : "\" - exe 'inoremap =coc#float#close_i('.winid.')' - exe 'nnoremap :call coc#float#close('.winid.')' - exe 'inoremap "\=coc#float#prompt_insert('.winid.')\\"' - call feedkeys('A', 'in') return [bufnr, winid] endfunction @@ -314,54 +561,19 @@ function! coc#float#close_i(winid) abort return '' endfunction -function! coc#float#prompt_insert(winid) abort - let text = getline('.') - let bufnr = winbufnr(a:winid) - call coc#rpc#notify('PromptInsert',[text, bufnr]) - call timer_start(50, { -> coc#float#close(a:winid)}) +function! coc#float#prompt_insert(text) abort + call coc#rpc#notify('PromptInsert', [a:text]) return '' endfunction -" Position of cursor relative to editor -function! s:win_position() abort - let nr = winnr() - let [row, col] = win_screenpos(nr) - return [row + winline() - 2, col + wincol() - 2] -endfunction - -" get popup position for vim8 based on config of neovim float window -function! s:popup_position(config) abort - let relative = get(a:config, 'relative', 'editor') - if relative ==# 'cursor' - return [s:popup_cursor(a:config['row']), s:popup_cursor(a:config['col'])] - endif - return [a:config['row'] + 1, a:config['col'] + 1] -endfunction - -function! s:popup_cursor(n) abort - if a:n == 0 - return 'cursor' - endif - if a:n < 0 - return 'cursor'.a:n - endif - return 'cursor+'.a:n -endfunction - " Close float window by id function! coc#float#close(winid) abort if !coc#float#valid(a:winid) return 0 endif - if s:is_vim - call popup_close(a:winid) - return 1 - else - call coc#float#nvim_close_related(a:winid) - call nvim_win_close(a:winid, 1) - return 1 - endif - return 0 + call coc#float#close_related(a:winid) + call s:close_win(a:winid) + return 1 endfunction " Float window id on current tab. @@ -395,10 +607,8 @@ function! coc#float#get_float_win_list() abort let id = win_getid(i) let config = nvim_win_get_config(id) " ignore border & button window - if (!empty(config) && config['focusable'] == v:true && !empty(config['relative'])) - if !getwinvar(id, 'button', 0) - call add(res, id) - endif + if (!empty(config) && !empty(config['relative']) && !getwinvar(id, 'target_winid', 0)) + call add(res, id) endif endfor return res @@ -414,7 +624,6 @@ function! coc#float#scrollable(winid) abort endif if s:is_vim let pos = popup_getpos(a:winid) - " scrollbar enabled if get(popup_getoptions(a:winid), 'scrollbar', 0) return get(pos, 'scrollbar', 0) endif @@ -438,135 +647,55 @@ function! coc#float#has_scroll() abort endfunction function! coc#float#scroll(forward, ...) - if !has('nvim-0.4.3') && !has('patch-8.2.0750') - throw 'coc#float#scroll() requires nvim >= 0.4.3 or vim >= 8.2.0750' + if !has('nvim-0.4.0') && !has('patch-8.2.0750') + throw 'coc#float#scroll() requires nvim >= 0.4.0 or vim >= 8.2.0750' endif let amount = get(a:, 1, 0) - let win_ids = filter(coc#float#get_float_win_list(), 'coc#float#scrollable(v:val)') - if empty(win_ids) + let winids = filter(coc#float#get_float_win_list(), 'coc#float#scrollable(v:val)') + if empty(winids) return '' endif - if has('nvim') - call timer_start(10, { -> s:scroll_nvim(win_ids, a:forward, amount)}) - else - call timer_start(10, { -> s:scroll_vim(win_ids, a:forward, amount)}) + for winid in winids + if s:is_vim + call coc#float#scroll_win(winid, a:forward, amount) + else + call timer_start(0, { -> coc#float#scroll_win(winid, a:forward, amount)}) + endif + endfor + return mode() =~ '^i' || mode() ==# 'v' ? "" : "\" +endfunction + +function! coc#float#scroll_win(winid, forward, amount) abort + let opts = s:get_options(a:winid) + let lines = getbufline(winbufnr(a:winid), 1, '$') + let maxfirst = s:max_firstline(lines, opts['height'], opts['width']) + let topline = opts['topline'] + let height = opts['height'] + let width = opts['width'] + let scrolloff = getwinvar(a:winid, '&scrolloff', 0) + if a:forward && topline >= maxfirst + return endif - return mode() =~ '^i' ? "" : "\" -endfunction - -function! s:scroll_nvim(win_ids, forward, amount) abort - let curr = win_getid() - for id in a:win_ids - if nvim_win_is_valid(id) - let wrapped = 0 - let width = nvim_win_get_width(id) - if getwinvar(id, '&wrap', 0) - if width > 1 && getwinvar(id, '&foldcolumn', 0) - let width = width - 1 - endif - for line in nvim_buf_get_lines(winbufnr(id), 0, -1, v:false) - if strdisplaywidth(line) > width - let wrapped = 1 - break - endif - endfor - endif - noa call win_gotoid(id) - let height = nvim_win_get_height(id) - let firstline = line('w0') - let lastline = line('w$') - let linecount = line('$') - let delta = a:amount ? a:amount : max([1, height - 1]) - if a:forward - if lastline == linecount && strdisplaywidth(line('$')) <= width - continue - endif - if !a:amount && firstline != lastline - execute 'noa normal! Lzt' - else - execute 'noa normal! H'.delta.'jzt' - endif - let lnum = line('.') - while lnum < linecount && line('w0') == firstline && line('w$') == lastline - execute 'noa normal! jzt' - let lnum = lnum + 1 - endwhile - else - if !a:amount && firstline != lastline - execute 'noa normal! Hzb' - else - execute 'noa normal! L'.delta.'kzb' - endif - let lnum = line('.') - while lnum > 1 && line('w0') == firstline && line('w$') == lastline - execute 'noa normal! kzb' - let lnum = lnum - 1 - endwhile - endif - call coc#float#nvim_scrollbar(id) + if !a:forward && topline == 1 + return + endif + if a:amount == 0 + let topline = s:get_topline(opts['topline'], lines, a:forward, height, width) + else + let topline = topline + (a:forward ? a:amount : - a:amount) + endif + let topline = a:forward ? min([maxfirst, topline]) : max([1, topline]) + let lnum = s:get_cursorline(topline, lines, scrolloff, width, height) + call s:win_setview(a:winid, topline, lnum) + let top = s:get_options(a:winid)['topline'] + " not changed + if top == opts['topline'] + if a:forward + call s:win_setview(a:winid, topline + 1, lnum + 1) + else + call s:win_setview(a:winid, topline - 1, lnum - 1) endif - endfor - noa call win_gotoid(curr) - redraw -endfunction - -function! s:scroll_vim(win_ids, forward, amount) abort - for id in a:win_ids - if s:popup_visible(id) - let pos = popup_getpos(id) - let bufnr = winbufnr(id) - let linecount = get(getbufinfo(bufnr)[0], 'linecount', 0) - " for forward use last line (or last line + 1) as first line - if a:forward - if pos['firstline'] == pos['lastline'] - call popup_setoptions(id, {'firstline': min([pos['firstline'] + 1, linecount])}) - else - if pos['lastline'] == linecount - let win_width = pos['core_width'] - let text = getbufline(bufnr, '$')[0] - if strdisplaywidth(text) <= win_width - " last line shown - return - endif - endif - let lnum = a:amount ? min([linecount, pos['firstline'] + a:amount]) : pos['lastline'] - call popup_setoptions(id, {'firstline': lnum}) - endif - else - if pos['firstline'] == 1 - call win_execute(id, 'normal! gg0') - return - endif - " we could only change firstline - " iterate lines before last lines to fill content height - 1 - let total_height = a:amount ? min([a:amount, pos['core_height']]) : pos['core_height'] - 1 - if total_height == 0 - call popup_setoptions(id, {'firstline': pos['firstline'] - 1}) - else - let lines = getbufline(bufnr, 1, '$') - let curr = pos['firstline'] - 1 - let width = pos['core_width'] - let used = 0 - while v:true - if curr == 1 - break - endif - let w = max([1, strdisplaywidth(lines[curr - 1])]) - let used += float2nr(ceil(str2float(string(w))/width)) - if used > total_height - let curr = curr == pos['firstline'] -1 ? curr : curr + 1 - break - elseif used == total_height - break - endif - let curr = curr - 1 - endwhile - call popup_setoptions(id, {'firstline': curr}) - endif - endif - endif - endfor - redraw + endif endfunction function! s:popup_visible(id) abort @@ -578,7 +707,8 @@ function! s:popup_visible(id) abort endfunction function! s:convert_config_nvim(config) abort - let result = coc#helper#dict_omit(a:config, ['title', 'border', 'cursorline', 'autohide', 'close']) + let valids = ['relative', 'win', 'anchor', 'width', 'height', 'bufpos', 'col', 'row', 'focusable', 'style'] + let result = coc#helper#dict_pick(a:config, valids) let border = get(a:config, 'border', []) if !s:empty_border(border) if result['relative'] ==# 'cursor' && result['row'] < 0 @@ -588,7 +718,7 @@ function! s:convert_config_nvim(config) abort endif else " move down when has top border - if get(border, 0, 0) + if get(border, 0, 0) && !get(a:config, 'prompt', 0) let result['row'] = result['row'] + 1 endif endif @@ -596,10 +726,11 @@ function! s:convert_config_nvim(config) abort if get(border, 3, 0) let result['col'] = result['col'] + 1 endif - let result['width'] = result['width'] + 1 - get(border,3, 0) + let result['width'] = float2nr(result['width'] + 1 - get(border,3, 0)) else - let result['width'] = result['width'] + 1 + let result['width'] = float2nr(result['width'] + 1) endif + let result['height'] = float2nr(result['height']) return result endfunction @@ -617,66 +748,6 @@ function! coc#float#close_auto_hide_wins(...) abort endfor endfunction -" neovim only -function! coc#float#nvim_close_btn(config, winid, close, border, related) abort - if !a:close - return - endif - let config = { - \ 'relative': a:config['relative'], - \ 'width': 1, - \ 'height': 1, - \ 'row': get(a:border, 0, 0) ? a:config['row'] - 1 : a:config['row'], - \ 'col': a:config['col'] + a:config['width'], - \ 'focusable': v:true, - \ 'style': 'minimal', - \ } - noa let bufnr = nvim_create_buf(v:false, v:true) - call setbufvar(bufnr, '&bufhidden', 'wipe') - call nvim_buf_set_lines(bufnr, 0, -1, v:false, ['X']) - let winid = nvim_open_win(bufnr, 0, config) - " map for winid & close_winid - if winid - call setwinvar(winid, 'button', 1) - call setwinvar(a:winid, 'close_winid', winid) - call setwinvar(winid, '&winhl', 'Normal:CocFloating,NormalNC:CocFloating') - call add(a:related, winid) - endif -endfunction - -function! coc#float#nvim_check_close(winid) abort - let target = getwinvar(a:winid, 'target_winid', 0) - if target - call coc#float#close(target) - endif -endfunction - -" Create padding window by config of current window & border config -function! coc#float#nvim_right_pad(config, border, related) abort - " Check right border - if !empty(a:border) && get(a:border, 1, 0) - return - endif - let config = { - \ 'relative': a:config['relative'], - \ 'width': 1, - \ 'height': a:config['height'], - \ 'row': a:config['row'], - \ 'col': a:config['col'] + a:config['width'], - \ 'focusable': v:false, - \ 'style': 'minimal', - \ } - noa let bufnr = nvim_create_buf(v:false, v:true) - call setbufvar(bufnr, '&bufhidden', 'wipe') - call nvim_buf_set_lines(bufnr, 0, -1, v:false, repeat([' '], a:config['height'])) - let winid = nvim_open_win(bufnr, 0, config) - if winid - call setwinvar(winid, 'ispad', 1) - call setwinvar(winid, '&winhl', 'Normal:CocFloating,NormalNC:CocFloating') - call add(a:related, winid) - endif -endfunction - function! coc#float#content_height(bufnr, width, wrap) abort if !bufloaded(a:bufnr) return 0 @@ -693,163 +764,70 @@ function! coc#float#content_height(bufnr, width, wrap) abort return total endfunction -function! s:add_related(winid, target) abort - let arr = getwinvar(a:target, 'related', []) - if index(arr, a:winid) >= 0 - return - endif - call add(arr, a:winid) - call setwinvar(a:target, 'related', arr) -endfunction - -function! coc#float#nvim_refresh_scrollbar() abort - let id = getwinvar(win_getid(), 'scrollbar', 0) - if coc#float#valid(id) - call coc#float#nvim_scrollbar(win_getid()) +function! coc#float#nvim_refresh_scrollbar(winid) abort + let id = coc#float#get_related(a:winid, 'scrollbar') + if id && nvim_win_is_valid(id) + call coc#float#nvim_scrollbar(a:winid) endif endfunction -" Close related windows for neovim. -function! coc#float#nvim_close_related(winid) abort - if !has('nvim') || !a:winid +" Close related windows, or specific kind +function! coc#float#close_related(winid, ...) abort + if !coc#float#valid(a:winid) return endif + let timer = getwinvar(a:winid, 'timer', 0) + if timer + call timer_stop(timer) + endif + let kind = get(a:, 1, '') let winids = getwinvar(a:winid, 'related', []) - if !empty(winids) - call nvim_win_del_var(a:winid, 'related') - endif for id in winids - if nvim_win_is_valid(id) && id != a:winid - call nvim_win_close(id, 1) + if s:is_vim + " vim doesn't throw + call popup_close(id) + elseif nvim_win_is_valid(id) + if empty(kind) || getwinvar(id, 'kind', '') ==# kind + noa call nvim_win_close(id, 1) + endif endif endfor endfunction -function! coc#float#nvim_create_related(winid, config, opts) abort - let related = [] - call coc#float#nvim_close_btn(a:config, a:winid, get(a:opts, 'close', 0), get(a:opts, 'border', []), related) - call coc#float#nvim_border_win(a:config, get(a:opts, 'border', []), get(a:opts, 'title', ''), related) - call coc#float#nvim_right_pad(a:config, get(a:opts, 'border', []), related) - for id in related - call setwinvar(id, 'target_winid', a:winid) - endfor - call setwinvar(a:winid, 'related', related) -endfunction - -" Create scrollbar for winid -" Need called on create, config, buffer change, scrolled -function! coc#float#nvim_scrollbar(winid) abort - if !has('nvim-0.4.3') - return - endif - if a:winid == 0 || !nvim_win_is_valid(a:winid) || getwinvar(a:winid, 'button', 0) - return - endif - let config = nvim_win_get_config(a:winid) - " ignore border & button window - if (!get(config, 'focusable', v:false) || empty(get(config, 'relative', ''))) - return - endif - let [row, column] = nvim_win_get_position(a:winid) - let width = nvim_win_get_width(a:winid) - let height = nvim_win_get_height(a:winid) - let bufnr = winbufnr(a:winid) - let cw = getwinvar(a:winid, '&foldcolumn', 0) ? width - 1 : width - let ch = coc#float#content_height(bufnr, cw, getwinvar(a:winid, '&wrap')) - let close_winid = getwinvar(a:winid, 'close_winid', 0) - let border = getwinvar(a:winid, 'border', []) - let move_down = close_winid && !get(border, 0, 0) - if move_down - let height = height - 1 - if height == 0 +" Close related windows if target window is not visible. +function! coc#float#check_related() abort + let invalids = [] + if s:is_vim + if !exists('*popup_list') return endif - endif - let id = 0 - if nvim_win_is_valid(getwinvar(a:winid, 'scrollbar', 0)) - let id = getwinvar(a:winid, 'scrollbar', 0) - endif - if ch <= height || height == 0 - " no scrollbar, remove exists - if id - call nvim_win_del_var(a:winid, 'scrollbar') - call coc#float#close(id) - endif - return - endif - if height == 0 - return - endif - if id && bufloaded(winbufnr(id)) - let sbuf = winbufnr(id) + for id in popup_list() + let target = getwinvar(id, 'target_winid', 0) + if (target && !s:popup_visible(target)) || getwinvar(id, 'kind', '') == 'pum' + call add(invalids, id) + endif + endfor else - noa let sbuf = nvim_create_buf(v:false, v:true) - call setbufvar(sbuf, '&bufhidden', 'wipe') + for i in range(1, winnr('$')) + let target = getwinvar(i, 'target_winid', 0) + if target && !nvim_win_is_valid(target) + call add(invalids, win_getid(i)) + elseif getwinvar(i, 'kind', '') == 'pum' + call add(invalids, win_getid(i)) + endif + endfor endif - call nvim_buf_set_lines(sbuf, 0, -1, v:false, repeat([' '], height)) - let opts = { - \ 'row': move_down ? row + 1 : row, - \ 'col': column + width, - \ 'relative': 'editor', - \ 'width': 1, - \ 'height': height, - \ 'focusable': v:false, - \ 'style': 'minimal', - \ } - if id - call nvim_win_set_config(id, opts) - else - let id = nvim_open_win(sbuf, 0 , opts) - call setwinvar(id, 'isscrollbar', 1) - call setwinvar(id, 'target_winid', a:winid) - endif - let thumb_height = max([1, float2nr(floor(height * (height + 0.0)/ch))]) - let curr = win_getid() - if curr != a:winid - noa call win_gotoid(a:winid) - endif - let firstline = line('w0') - let lastline = line('w$') - let linecount = line('$') - if firstline == 1 - let start = 0 - elseif lastline == linecount - let start = height - thumb_height - else - let start = max([1, float2nr(round((height - thumb_height + 0.0)*(firstline - 1.0)/(ch - height)))]) - endif - if curr != a:winid - noa call win_gotoid(curr) - endif - " add highlights - call nvim_buf_clear_namespace(sbuf, s:scrollbar_ns, 0, -1) - for idx in range(0, height - 1) - if idx >= start && idx < start + thumb_height - call nvim_buf_add_highlight(sbuf, s:scrollbar_ns, 'PmenuThumb', idx, 0, 1) - else - call nvim_buf_add_highlight(sbuf, s:scrollbar_ns, 'PmenuSbar', idx, 0, 1) - endif + for id in invalids + call coc#float#close(id) endfor - " create scrollbar outside window - call setwinvar(a:winid, 'scrollbar', id) - call s:add_related(id, a:winid) endfunction -function! coc#float#nvim_check_related() abort - if !has('nvim') - return - endif - let invalids = [] - for i in range(1, winnr('$')) - let id = win_getid(i) - let target = getwinvar(id, 'target_winid', 0) - if target && !nvim_win_is_valid(target) - call add(invalids, id) - endif - endfor - for id in invalids - noa call nvim_win_close(id, 1) - endfor +" Scroll float in any mode (neovim only) +" Only really useful for visual mode scroll, where coc#float#scroll +" is not yet implemented +function! coc#float#nvim_scroll(forward, ...) + echohl WarningMsg | echon 'coc#float#nvim_scroll is removed, use coc#float#scroll instead' | echohl None + return '' endfunction " Dimension of window with lines relative to cursor @@ -866,33 +844,33 @@ function! coc#float#get_config_cursor(lines, config) abort if vh <= 0 return v:null endif - let maxWidth = min([get(a:config, 'maxWidth', 80), &columns - 1]) + let maxWidth = coc#helper#min(get(a:config, 'maxWidth', &columns - 1), &columns - 1) if maxWidth < 3 return v:null endif - let maxHeight = min([get(a:config, 'maxHeight', 80), vh]) + let maxHeight = coc#helper#min(get(a:config, 'maxHeight', vh), vh) let ch = 0 - let width = min([40, strdisplaywidth(title)]) + 3 + let width = coc#helper#min(40, strdisplaywidth(title)) + 3 for line in a:lines let dw = max([1, strdisplaywidth(line)]) let width = max([width, dw + 2]) let ch += float2nr(ceil(str2float(string(dw))/(maxWidth - 2))) endfor - let width = min([maxWidth, width]) - let [lineIdx, colIdx] = s:win_position() + let width = coc#helper#min(maxWidth, width) + let [lineIdx, colIdx] = coc#util#cursor_pos() " How much we should move left - let offsetX = min([get(a:config, 'offsetX', 0), colIdx]) + let offsetX = coc#helper#min(get(a:config, 'offsetX', 0), colIdx) let showTop = 0 let hb = vh - lineIdx -1 if lineIdx > bh + 2 && (preferTop || (lineIdx > hb && hb < ch + bh)) let showTop = 1 endif - let height = min([maxHeight, ch + bh, showTop ? lineIdx - 1 : hb]) + let height = coc#helper#min(maxHeight, ch + bh, showTop ? lineIdx - 1 : hb) if height <= bh return v:null endif let col = - max([offsetX, colIdx - (&columns - 1 - width)]) - let row = showTop ? - height : 1 + let row = showTop ? - height + bh : 1 return { \ 'row': row, \ 'col': col, @@ -901,15 +879,16 @@ function! coc#float#get_config_cursor(lines, config) abort \ } endfunction -function! coc#float#get_config_pum(lines, pumconfig, maxwidth) abort - if !pumvisible() +function! coc#float#create_pum_float(winid, bufnr, lines, config) abort + if !pumvisible() || !s:float_supported return v:null endif - let pw = a:pumconfig['width'] + get(a:pumconfig, 'scrollbar', 0) - let rp = &columns - a:pumconfig['col'] - pw - let showRight = a:pumconfig['col'] > rp ? 0 : 1 - let maxWidth = showRight ? min([rp - 1, a:maxwidth]) : min([a:pumconfig['col'] - 1, a:maxwidth]) - let maxHeight = &lines - a:pumconfig['row'] - &cmdheight - 1 + let pumbounding = a:config['pumbounding'] + let pw = pumbounding['width'] + get(pumbounding, 'scrollbar', 0) + let rp = &columns - pumbounding['col'] - pw + let showRight = pumbounding['col'] > rp ? 0 : 1 + let maxWidth = showRight ? coc#helper#min(rp - 1, a:config['maxWidth']) : coc#helper#min(pumbounding['col'] - 1, a:config['maxWidth']) + let maxHeight = &lines - pumbounding['row'] - &cmdheight - 1 if maxWidth <= 2 || maxHeight < 1 return v:null endif @@ -920,15 +899,29 @@ function! coc#float#get_config_pum(lines, pumconfig, maxwidth) abort let width = max([width, dw + 2]) let ch += float2nr(ceil(str2float(string(dw))/(maxWidth - 2))) endfor - let width = min([maxWidth, width]) - let height = min([maxHeight, ch]) - return { - \ 'col': showRight ? a:pumconfig['col'] + pw : a:pumconfig['col'] - width - 1, - \ 'row': a:pumconfig['row'], - \ 'height': height, - \ 'width': width - 2 + (s:is_vim && ch > height ? -1 : 0), - \ 'relative': 'editor' - \ } + let width = float2nr(coc#helper#min(maxWidth, width)) + let height = float2nr(coc#helper#min(maxHeight, ch)) + let lines = map(a:lines, {_, s -> s =~# '^—' ? repeat('—', width - 2 + (s:is_vim && ch > height ? -1 : 0)) : s}) + let opts = { + \ 'lines': lines, + \ 'relative': 'editor', + \ 'col': showRight ? pumbounding['col'] + pw : pumbounding['col'] - width - 1, + \ 'row': pumbounding['row'], + \ 'height': height, + \ 'width': width - 2 + (s:is_vim && ch > height ? -1 : 0), + \ } + call coc#float#close_auto_hide_wins(a:winid) + let res = coc#float#create_float_win(a:winid, a:bufnr, opts) + if empty(res) + return v:null + endif + call coc#highlight#add_highlights(res[0], a:config['codes'], a:config['highlights']) + call setwinvar(res[0], 'kind', 'pum') + redraw + if has('nvim') + call coc#float#nvim_scrollbar(res[0]) + endif + return res endfunction function! s:empty_border(border) abort @@ -940,3 +933,812 @@ function! s:empty_border(border) abort endif return 0 endfunction + +" Show float window/popup for user confirm. +function! coc#float#prompt_confirm(title, cb) abort + if s:is_vim && exists('*popup_dialog') + try + call popup_dialog(a:title. ' (y/n)?', { + \ 'highlight': 'Normal', + \ 'filter': 'popup_filter_yesno', + \ 'callback': {id, res -> a:cb(v:null, res)}, + \ 'borderchars': s:borderchars, + \ 'borderhighlight': ['MoreMsg'] + \ }) + catch /.*/ + call a:cb(v:exception) + endtry + return + endif + if has('nvim-0.4.0') + let text = ' '. a:title . ' (y/n)? ' + let maxWidth = coc#helper#min(78, &columns - 2) + let width = coc#helper#min(maxWidth, strdisplaywidth(text)) + let maxHeight = &lines - &cmdheight - 1 + let height = coc#helper#min(maxHeight, float2nr(ceil(str2float(string(strdisplaywidth(text)))/width))) + call coc#float#close_auto_hide_wins() + let arr = coc#float#create_float_win(0, s:prompt_win_bufnr, { + \ 'col': &columns/2 - width/2 - 1, + \ 'row': maxHeight/2 - height/2 - 1, + \ 'width': width, + \ 'height': height, + \ 'border': [1,1,1,1], + \ 'focusable': v:false, + \ 'relative': 'editor', + \ 'highlight': 'Normal', + \ 'borderhighlight': ['MoreMsg'], + \ 'style': 'minimal', + \ 'lines': [text], + \ }) + if empty(arr) + call a:cb('Window create failed!') + return + endif + let winid = arr[0] + let s:prompt_win_bufnr = arr[1] + let res = 0 + redraw + " same result as vim + while 1 + let key = nr2char(getchar()) + if key == "\" + let res = -1 + break + elseif key == "\" || key == 'n' || key == 'N' + let res = 0 + break + elseif key == 'y' || key == 'Y' + let res = 1 + break + endif + endw + call coc#float#close(winid) + call a:cb(v:null, res) + " use relative editor since neovim doesn't support center position + elseif exists('*confirm') + let choice = confirm(a:title, "&Yes\n&No") + call a:cb(v:null, choice == 1) + else + echohl MoreMsg + echom a:title.' (y/n)' + echohl None + let confirm = nr2char(getchar()) + redraw! + if !(confirm ==? "y" || confirm ==? "\r") + echohl Moremsg | echo 'Cancelled.' | echohl None + return 0 + call a:cb(v:null, 0) + end + call a:cb(v:null, 1) + endif +endfunction + +" Create buttons popup on vim +function! coc#float#vim_buttons(winid, config) abort + if !has('patch-8.2.0750') + return + endif + let related = getwinvar(a:winid, 'related', []) + let winid = coc#float#get_related(a:winid, 'buttons') + let btns = get(a:config, 'buttons', []) + if empty(btns) + if winid + call s:close_win(winid) + " fix padding + let opts = popup_getoptions(a:winid) + let padding = get(opts, 'padding', v:null) + if !empty(padding) + let padding[2] = padding[2] - 2 + endif + call popup_setoptions(a:winid, {'padding': padding}) + endif + return + endif + let border = get(a:config, 'border', v:null) + if !winid + " adjusting popup padding + let opts = popup_getoptions(a:winid) + let padding = get(opts, 'padding', v:null) + if type(padding) == 7 + let padding = [0, 0, 2, 0] + elseif len(padding) == 0 + let padding = [1, 1, 3, 1] + else + let padding[2] = padding[2] + 2 + endif + call popup_setoptions(a:winid, {'padding': padding}) + endif + let borderhighlight = get(get(a:config, 'borderhighlight', []), 0, '') + let pos = popup_getpos(a:winid) + let bw = empty(border) ? 0 : get(border, 1, 0) + get(border, 3, 0) + let borderbottom = empty(border) ? 0 : get(border, 2, 0) + let borderleft = empty(border) ? 0 : get(border, 3, 0) + let width = pos['width'] - bw + get(pos, 'scrollbar', 0) + let bufnr = s:create_btns_buffer(winid ? winbufnr(winid): 0,width, btns, borderbottom) + let height = 2 + (borderbottom ? 1 : 0) + let keys = s:gen_filter_keys(getbufline(bufnr, 2)[0]) + let options = { + \ 'filter': {id, key -> coc#float#vim_filter(id, key, keys[1])}, + \ 'highlight': get(opts, 'highlight', 'CocFloating') + \ } + let config = { + \ 'line': pos['line'] + pos['height'] - height, + \ 'col': pos['col'] + borderleft, + \ 'minwidth': width, + \ 'minheight': height, + \ 'maxwidth': width, + \ 'maxheight': height, + \ } + if winid != 0 + call popup_move(winid, config) + call popup_setoptions(winid, options) + call win_execute(winid, 'call clearmatches()') + else + let options = extend({ + \ 'filtermode': 'nvi', + \ 'padding': [0, 0, 0, 0], + \ 'fixed': 1, + \ 'zindex': 99, + \ }, options) + call extend(options, config) + let winid = popup_create(bufnr, options) + endif + if winid != 0 + if !empty(borderhighlight) + call coc#highlight#add_highlight(bufnr, -1, borderhighlight, 0, 0, -1) + call coc#highlight#add_highlight(bufnr, -1, borderhighlight, 2, 0, -1) + call win_execute(winid, 'call matchadd("'.borderhighlight.'", "'.s:borderchars[1].'")') + endif + call setwinvar(winid, 'kind', 'buttons') + call setwinvar(winid, 'target_winid', a:winid) + call add(related, winid) + call setwinvar(a:winid, 'related', related) + call matchaddpos('MoreMsg', map(keys[0], "[2,v:val]"), 99, -1, {'window': winid}) + endif +endfunction + +function! coc#float#nvim_float_click() abort + let kind = getwinvar(win_getid(), 'kind', '') + if kind == 'buttons' + if line('.') != 2 + return + endif + let vw = strdisplaywidth(strpart(getline('.'), 0, col('.') - 1)) + let vcols = getbufvar(bufnr('%'), 'vcols', []) + if index(vcols, vw) >= 0 + return + endif + let idx = 0 + if !empty(vcols) + let filtered = filter(vcols, 'v:val < vw') + let idx = idx + len(filtered) + endif + let winid = win_getid() + let target = getwinvar(winid, 'target_winid', 0) + if target + call coc#rpc#notify('FloatBtnClick', [winbufnr(target), idx]) + call coc#float#close(target) + endif + elseif kind == 'close' + let target = getwinvar(win_getid(), 'target_winid', 0) + call coc#float#close(target) + endif +endfunction + +" Add mapping if necessary +function! coc#float#nvim_win_enter(winid) abort + let kind = getwinvar(a:winid, 'kind', '') + if kind == 'buttons' || kind == 'close' + if empty(maparg('', 'n')) + nnoremap :call coc#float#nvim_float_click() + endif + endif +endfunction + +function! coc#float#vim_filter(winid, key, keys) abort + let key = tolower(a:key) + let idx = index(a:keys, key) + let target = getwinvar(a:winid, 'target_winid', 0) + if target && idx >= 0 + call coc#rpc#notify('FloatBtnClick', [winbufnr(target), idx]) + call coc#float#close(target) + return 1 + endif + return 0 +endfunction + +" Create dialog at center +function! coc#float#create_dialog(lines, config) abort + " dialog always have borders + let title = get(a:config, 'title', '') + let buttons = get(a:config, 'buttons', []) + let highlight = get(a:config, 'highlight', 'CocFloating') + let borderhighlight = get(a:config, 'borderhighlight', [highlight]) + let maxheight = coc#helper#min(get(a:config, 'maxHeight', 78), &lines - &cmdheight - 6) + let maxwidth = coc#helper#min(get(a:config, 'maxWidth', 78), &columns - 2) + let close = get(a:config, 'close', 1) + let minwidth = s:min_btns_width(buttons) + if maxheight <= 0 || maxwidth <= 0 || minwidth > maxwidth + throw 'Not enough spaces for dialog' + endif + let ch = 0 + let width = coc#helper#min(strdisplaywidth(title) + 1, maxwidth) + for line in a:lines + let dw = max([1, strdisplaywidth(line)]) + if dw < maxwidth && dw > width + let width = dw + elseif dw > maxwidth + let width = maxwidth + endif + let ch += float2nr(ceil(str2float(string(dw))/maxwidth)) + endfor + let width = max([minwidth, width]) + let height = coc#helper#min(ch ,maxheight) + let opts = { + \ 'relative': 'editor', + \ 'col': &columns/2 - (width + 2)/2, + \ 'row': &lines/2 - (height + 4)/2, + \ 'width': width, + \ 'height': height, + \ 'border': [1,1,1,1], + \ 'title': title, + \ 'close': close, + \ 'highlight': highlight, + \ 'buttons': buttons, + \ 'borderhighlight': borderhighlight, + \ } + if get(a:config, 'cursorline', 0) + let opts['cursorline'] = 1 + endif + let bufnr = coc#float#create_buf(0, a:lines) + call coc#float#close_auto_hide_wins() + let res = coc#float#create_float_win(0, bufnr, opts) + if empty(res) + return + endif + if has('nvim') + if get(a:config, 'cursorline', 0) + execute 'sign place 6 line=1 name=CocCurrentLine buffer='.bufnr + endif + redraw + call coc#float#nvim_scrollbar(res[0]) + endif + return res +endfunction + +function! coc#float#get_related(winid, kind) abort + for winid in getwinvar(a:winid, 'related', []) + if getwinvar(winid, 'kind', '') ==# a:kind + return winid + endif + endfor + return 0 +endfunction + +" Create temporarily buffer with optional lines and &bufhidden +function! coc#float#create_buf(bufnr, ...) abort + if a:bufnr > 0 && bufloaded(a:bufnr) + let bufnr = a:bufnr + else + if s:is_vim + noa let bufnr = bufadd('') + noa call bufload(bufnr) + call setbufvar(bufnr, '&buflisted', 0) + else + noa let bufnr = nvim_create_buf(v:false, v:true) + endif + let bufhidden = get(a:, 2, 'wipe') + call setbufvar(bufnr, '&buftype', 'nofile') + call setbufvar(bufnr, '&bufhidden', bufhidden) + call setbufvar(bufnr, '&swapfile', 0) + call setbufvar(bufnr, '&undolevels', -1) + " neovim's bug + call setbufvar(bufnr, '&modifiable', 1) + endif + let lines = get(a:, 1, v:null) + if type(lines) != 7 + if has('nvim') + call nvim_buf_set_lines(bufnr, 0, -1, v:false, lines) + else + call deletebufline(bufnr, 1, '$') + call setbufline(bufnr, 1, lines) + endif + endif + return bufnr +endfunction + +function! coc#float#create_menu(lines, config) abort + let highlight = get(a:config, 'highlight', 'CocFloating') + let borderhighlight = get(a:config, 'borderhighlight', [highlight]) + let opts = { + \ 'lines': a:lines, + \ 'highlight': highlight, + \ 'title': get(a:config, 'title', ''), + \ 'borderhighlight': borderhighlight, + \ 'maxWidth': get(a:config, 'maxWidth', 80), + \ 'maxHeight': get(a:config, 'maxHeight', 80), + \ 'border': [1, 1, 1, 1], + \ 'relative': 'cursor', + \ } + if s:is_vim + let opts['cursorline'] = 1 + endif + let dimension = coc#float#get_config_cursor(a:lines, opts) + call extend(opts, dimension) + call coc#float#close_auto_hide_wins() + let res = coc#float#create_float_win(0, s:prompt_win_bufnr, opts) + if empty(res) + return + endif + let s:prompt_win_bufnr = res[1] + redraw + if has('nvim') + call coc#float#nvim_scrollbar(res[0]) + execute 'sign unplace 6 buffer='.s:prompt_win_bufnr + execute 'sign place 6 line=1 name=CocCurrentLine buffer='.s:prompt_win_bufnr + endif + return res +endfunction + +" Notification always have border +" config including: +" - title: optional title. +" - close: default to 1 +" - borderhighlight: highlight group string +" - timeout: timeout in miniseconds +" - buttons: array of button text for create buttons at bottom. +" - top: default to 1 +" - right: default to 1 +" - maxHeight: default to 10 +" - maxWidth: default to 60 +" - highlight: highlight of window, default to 'CocFloating' +function! coc#float#create_notification(lines, config) abort + let close = get(a:config, 'close', 1) + let timeout = get(a:config, 'timeout', 0) + let borderhighlight = get(a:config, 'borderhighlight', 'CocFloating') + let highlight = get(a:config, 'highlight', 'CocFloating') + let title = get(a:config, 'title', '') + let top = get(a:config, 'top', 1) + let right = get(a:config, 'right', 1) + let buttons = get(a:config, 'buttons', []) + let maxHeight = get(a:config, 'maxHeight', 10) + let maxWidth = min([&columns - right - 10, get(a:config, 'maxWidth', 60)]) + let progress = get(a:config, 'progress', 0) + let minWidth = get(a:config, 'minWidth', 1) + let minWidth = max([minWidth, s:min_btns_width(buttons)]) + if &columns < right + 10 || minWidth > maxWidth + throw 'no enough spaces for notification' + endif + let width = min([maxWidth, max(map(a:lines + [title + ' '], "strdisplaywidth(v:val)"))]) + let width = max([minWidth, width]) + let height = 0 + for line in a:lines + let w = max([1, strdisplaywidth(line)]) + let height += float2nr(ceil(str2float(string(w))/width)) + endfor + let height = min([maxHeight, height, &lines - &cmdheight - 1]) + let col = &columns - right - width - 2 + let opts = { + \ 'row': top, + \ 'col': col, + \ 'lines': a:lines, + \ 'relative': 'editor', + \ 'width': width, + \ 'height': height, + \ 'highlight': highlight, + \ 'borderhighlight': [borderhighlight], + \ 'border': [1, 1, 1, 1], + \ 'title': title, + \ 'close': close, + \ 'buttons': buttons, + \ } + call coc#float#reflow(top + height + 2 + (empty(buttons) ? 0 : 2)) + let res = coc#float#create_float_win(0, 0, opts) + if empty(res) + return + endif + let [winid, bufnr] = res + call setwinvar(winid, 'kind', 'notification') + redraw + if has('nvim') + call coc#float#nvim_scrollbar(winid) + endif + if timeout + call timer_start(timeout, { -> coc#float#close(winid)}) + endif + if progress + let start = reltime() + let timer = timer_start(16, { -> s:update_progress(bufnr, width, reltimefloat(reltime(start)))}, { + \ 'repeat': -1 + \ }) + call setwinvar(winid, 'timer', timer) + endif + return res +endfunction + +" adjust position for notification windows +function! coc#float#reflow(top) abort + let winids = coc#float#get_float_win_list() + let optlist = [] + for winid in winids + if getwinvar(winid, 'kind', '') !=# 'notification' + continue + endif + call add(optlist, s:get_win_opts(winid)) + endfor + call sort(optlist, {a, b -> a['row'] - b['row']}) + "echo optlist + let top = a:top + for opts in optlist + if opts['row'] <= top + let changed = top + 1 - opts['row'] + let opts['row'] = top + 1 + call s:adjust_win_row(opts['winid'], changed) + endif + " adjust top + let top = opts['row'] + opts['height'] + endfor +endfunction + +" float/popup relative to current cursor position +function! coc#float#cursor_relative(winid) abort + if !coc#float#valid(a:winid) + return v:null + endif + let winid = win_getid() + if winid == a:winid + return v:null + endif + let [cursorLine, cursorCol] = coc#util#cursor_pos() + if has('nvim') + let [row, col] = nvim_win_get_position(a:winid) + return {'row' : row - cursorLine, 'col' : col - cursorCol} + endif + let pos = popup_getpos(a:winid) + return {'row' : pos['line'] - cursorLine - 1, 'col' : pos['col'] - cursorCol - 1} +endfunction + +" move winid include relative windows. +function! s:adjust_win_row(winid, changed) abort + let ids = getwinvar(a:winid, 'related', []) + if s:is_vim + let pos = popup_getpos(a:winid) + if pos['line'] - 1 + a:changed + pos['height'] > &lines - &cmdheight + call coc#float#close(a:winid) + return + endif + call popup_move(a:winid, { + \ 'line': pos['line'] + a:changed + \ }) + for winid in ids + let winpos = popup_getpos(winid) + call popup_move(winid, { + \ 'line': winpos['line'] + a:changed + \ }) + endfor + else + let ids = [a:winid] + ids + " close it if it's fully shown + let borderwin = coc#float#get_related(a:winid, 'border') + let winid = borderwin == 0 ? a:winid : borderwin + let height = nvim_win_get_height(winid) + let pos = nvim_win_get_position(winid) + if pos[0] + a:changed + height > &lines - &cmdheight + call coc#float#close(a:winid) + return + endif + for winid in ids + let [row, col] = nvim_win_get_position(winid) + call nvim_win_set_config(winid, { + \ 'relative': 'editor', + \ 'row': row + a:changed, + \ 'col': col, + \ }) + endfor + endif +endfunction + +" winid, width, height, row, col (0 based). +" works on vim & neovim, check relative window +function! s:get_win_opts(winid) abort + if s:is_vim + let pos = popup_getpos(a:winid) + return { + \ 'winid': a:winid, + \ 'row': pos['line'] - 1, + \ 'col': pos['col'] - 1, + \ 'width': pos['width'], + \ 'height': pos['height'], + \ } + else + let borderwin = coc#float#get_related(a:winid, 'border') + let winid = borderwin == 0 ? a:winid : borderwin + let [row, col] = nvim_win_get_position(winid) + return { + \ 'winid': a:winid, + \ 'row': row, + \ 'col': col, + \ 'width': nvim_win_get_width(winid), + \ 'height': nvim_win_get_height(winid) + \ } + endif +endfunction + +function! s:create_btns_buffer(bufnr, width, buttons, borderbottom) abort + let n = len(a:buttons) + let spaces = a:width - n + 1 + let tw = 0 + for txt in a:buttons + let tw += strdisplaywidth(txt) + endfor + if spaces < tw + throw 'window is too small for buttons.' + endif + let ds = (spaces - tw)/n + let dl = ds/2 + let dr = ds%2 == 0 ? ds/2 : ds/2 + 1 + let btnline = '' + let idxes = [] + for idx in range(0, n - 1) + let txt = toupper(a:buttons[idx][0]).a:buttons[idx][1:] + let btnline .= repeat(' ', dl).txt.repeat(' ', dr) + if idx != n - 1 + call add(idxes, strdisplaywidth(btnline)) + let btnline .= s:borderchars[1] + endif + endfor + let lines = [repeat(s:borderchars[0], a:width), btnline] + if a:borderbottom + call add(lines, repeat(s:borderchars[0], a:width)) + endif + for idx in idxes + let lines[0] = strcharpart(lines[0], 0, idx).s:borderjoinchars[0].strcharpart(lines[0], idx + 1) + if a:borderbottom + let lines[2] = strcharpart(lines[0], 0, idx).s:borderjoinchars[2].strcharpart(lines[0], idx + 1) + endif + endfor + let bufnr = coc#float#create_buf(a:bufnr, lines) + call setbufvar(bufnr, 'vcols', idxes) + return bufnr +endfunction + +function! s:gen_filter_keys(line) abort + let cols = [] + let used = [] + let next = 1 + for idx in range(0, strchars(a:line) - 1) + let ch = strcharpart(a:line, idx, 1) + let nr = char2nr(ch) + if next + if (nr >= 65 && nr <= 90) || (nr >= 97 && nr <= 122) + let lc = tolower(ch) + if index(used, lc) < 0 && empty(maparg(lc, 'n')) + let col = len(strcharpart(a:line, 0, idx)) + 1 + call add(used, lc) + call add(cols, col) + let next = 0 + endif + endif + else + if ch == s:borderchars[1] + let next = 1 + endif + endif + endfor + return [cols, used] +endfunction + +function! s:close_win(winid) abort + if a:winid == 0 + return + endif + " vim not throw for none exists winid + if s:is_vim + call popup_close(a:winid) + else + if nvim_win_is_valid(a:winid) + call nvim_win_close(a:winid, 1) + endif + endif +endfunction + +function! s:nvim_create_keymap(winid) abort + if a:winid == 0 + return + endif + let curr = win_getid() + " nvim should support win_execute so we don't break visual mode. + let m = mode() + if m == 'n' || m == 'i' || m == 'ic' + noa call win_gotoid(a:winid) + nnoremap :call coc#float#nvim_float_click() + noa call win_gotoid(curr) + endif +endfunction + +" getwininfo is buggy on neovim, use topline, width & height should for content +function! s:nvim_get_botline(topline, height, width, bufnr) abort + let lines = getbufline(a:bufnr, a:topline, a:topline + a:height - 1) + let botline = a:topline + let count = 0 + for i in range(0, len(lines) - 1) + let w = coc#helper#max(1, strdisplaywidth(lines[i])) + let lh = float2nr(ceil(str2float(string(w))/a:width)) + let count = count + lh + let botline = a:topline + i + if count >= a:height + break + endif + endfor + return botline +endfunction + +" get popup position for vim8 based on config of neovim float window +function! s:popup_position(config) abort + let relative = get(a:config, 'relative', 'editor') + if relative ==# 'cursor' + return [s:popup_cursor(a:config['row']), s:popup_cursor(a:config['col'])] + endif + return [a:config['row'] + 1, a:config['col'] + 1] +endfunction + +function! s:add_related(winid, target) abort + let arr = getwinvar(a:target, 'related', []) + if index(arr, a:winid) >= 0 + return + endif + call add(arr, a:winid) + call setwinvar(a:target, 'related', arr) +endfunction + +function! s:popup_cursor(n) abort + if a:n == 0 + return 'cursor' + endif + if a:n < 0 + return 'cursor'.a:n + endif + return 'cursor+'.a:n +endfunction + +function! s:is_blocking() abort + if coc#prompt#activated() + return 1 + endif + return 0 +endfunction + +" max firstline of lines, height > 0, width > 0 +function! s:max_firstline(lines, height, width) abort + let max = len(a:lines) + let remain = a:height + for line in reverse(copy(a:lines)) + let w = max([1, strdisplaywidth(line)]) + let dh = float2nr(ceil(str2float(string(w))/a:width)) + if remain - dh < 0 + break + endif + let remain = remain - dh + let max = max - 1 + endfor + return min([len(a:lines), max + 1]) +endfunction + +" Get best lnum by topline +function! s:get_cursorline(topline, lines, scrolloff, width, height) abort + let lastline = len(a:lines) + if a:topline == lastline + return lastline + endif + let bottomline = a:topline + let used = 0 + for lnum in range(a:topline, lastline) + let w = max([1, strdisplaywidth(a:lines[lnum - 1])]) + let dh = float2nr(ceil(str2float(string(w))/a:width)) + if used + dh >= a:height || lnum == lastline + let bottomline = lnum + break + endif + let used += dh + endfor + let cursorline = a:topline + a:scrolloff + if cursorline + a:scrolloff > bottomline + " unable to satisfy scrolloff + let cursorline = (a:topline + bottomline)/2 + endif + return cursorline +endfunction + +" Get firstline for full scroll +function! s:get_topline(topline, lines, forward, height, width) abort + let used = 0 + let lnums = a:forward ? range(a:topline, len(a:lines)) : reverse(range(1, a:topline)) + let topline = a:forward ? len(a:lines) : 1 + for lnum in lnums + let w = max([1, strdisplaywidth(a:lines[lnum - 1])]) + let dh = float2nr(ceil(str2float(string(w))/a:width)) + if used + dh >= a:height + let topline = lnum + break + endif + let used += dh + endfor + if topline == a:topline + if a:forward + let topline = min([len(a:lines), topline + 1]) + else + let topline = max([1, topline - 1]) + endif + endif + return topline +endfunction + +" topline content_height content_width +function! s:get_options(winid) abort + if has('nvim') + let width = nvim_win_get_width(a:winid) + if getwinvar(a:winid, '&foldcolumn', 0) + let width = width - 1 + endif + let info = getwininfo(a:winid)[0] + return { + \ 'topline': info['topline'], + \ 'height': nvim_win_get_height(a:winid), + \ 'width': width + \ } + else + let pos = popup_getpos(a:winid) + return { + \ 'topline': pos['firstline'], + \ 'width': pos['core_width'], + \ 'height': pos['core_height'] + \ } + endif +endfunction + +function! s:win_setview(winid, topline, lnum) abort + if has('nvim') + call coc#compat#execute(a:winid, 'call winrestview({"lnum":'.a:lnum.',"topline":'.a:topline.'})') + call timer_start(10, { -> coc#float#nvim_refresh_scrollbar(a:winid) }) + else + call coc#compat#execute(a:winid, 'exe '.a:lnum) + call popup_setoptions(a:winid, { + \ 'firstline': a:topline, + \ }) + endif +endfunction + +function! s:min_btns_width(buttons) abort + if empty(a:buttons) + return 0 + endif + let minwidth = len(a:buttons)*3 - 1 + for txt in a:buttons + let minwidth = minwidth + strdisplaywidth(txt) + endfor + return minwidth +endfunction + +function! s:update_progress(bufnr, width, ts) abort + let duration = 5000 + " count of blocks + let width = float2nr((a:width + 0.0)/4) + let percent = (float2nr(a:ts*1000)%duration + 0.0)/duration + let line = repeat(s:progresschars[0], a:width) + let startIdx = float2nr(round(a:width * percent)) + let endIdx = startIdx + width + let delta = a:width - endIdx + if delta > 0 + let line = s:str_compose(line, startIdx, repeat(s:progresschars[1], width)) + else + let inserted = repeat(s:progresschars[1], width + delta) + let line = s:str_compose(line, startIdx, inserted) + let line = s:str_compose(line, 0, repeat(s:progresschars[1], - delta)) + endif + call setbufline(a:bufnr, 1, line) +endfunction + +function! s:str_compose(line, idx, text) abort + let first = strcharpart(a:line, 0, a:idx) + return first.a:text.strcharpart(a:line, a:idx + strwidth(a:text)) +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/helper.vim b/pack/acp/opt/coc.nvim/autoload/coc/helper.vim index ae7eab2..08cb5ec 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/helper.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/helper.vim @@ -54,3 +54,36 @@ function! coc#helper#dict_omit(dict, keys) abort endfor return res endfunction + +" Return new dict with keys only +function! coc#helper#dict_pick(dict, keys) abort + let res = {} + for key in keys(a:dict) + if index(a:keys, key) != -1 + let res[key] = a:dict[key] + endif + endfor + return res +endfunction + +" support for float values +function! coc#helper#min(first, ...) abort + let val = a:first + for i in range(0, len(a:000) - 1) + if a:000[i] < val + let val = a:000[i] + endif + endfor + return val +endfunction + +" support for float values +function! coc#helper#max(first, ...) abort + let val = a:first + for i in range(0, len(a:000) - 1) + if a:000[i] > val + let val = a:000[i] + endif + endfor + return val +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/highlight.vim b/pack/acp/opt/coc.nvim/autoload/coc/highlight.vim new file mode 100644 index 0000000..e646a8d --- /dev/null +++ b/pack/acp/opt/coc.nvim/autoload/coc/highlight.vim @@ -0,0 +1,321 @@ +let s:is_vim = !has('nvim') +let s:clear_match_by_window = has('nvim-0.5.0') || has('patch-8.1.1084') +let s:namespace_map = {} +let s:ns_id = 1 + +if has('nvim-0.5.0') + try + call getmatches(0) + catch /^Vim\%((\a\+)\)\=:E118/ + let s:clear_match_by_window = 0 + endtry +endif + +" highlight LSP range, +function! coc#highlight#ranges(bufnr, key, hlGroup, ranges) abort + let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr + if !bufloaded(bufnr) || !exists('*getbufline') + return + endif + let srcId = s:create_namespace(a:key) + for range in a:ranges + let start = range['start'] + let end = range['end'] + for lnum in range(start['line'] + 1, end['line'] + 1) + let arr = getbufline(bufnr, lnum) + let line = empty(arr) ? '' : arr[0] + if empty(line) + continue + endif + " TODO don't know how to count UTF16 code point, should work most cases. + let colStart = lnum == start['line'] + 1 ? strlen(strcharpart(line, 0, start['character'])) : 0 + let colEnd = lnum == end['line'] + 1 ? strlen(strcharpart(line, 0, end['character'])) : -1 + if colStart == colEnd + continue + endif + call coc#highlight#add_highlight(bufnr, srcId, a:hlGroup, lnum - 1, colStart, colEnd) + endfor + endfor +endfunction + +function! coc#highlight#add_highlight(bufnr, src_id, hl_group, line, col_start, col_end) abort + if has('nvim') + call nvim_buf_add_highlight(a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end) + else + call coc#api#call('buf_add_highlight', [a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end]) + endif +endfunction + +function! coc#highlight#clear_highlight(bufnr, key, start_line, end_line) abort + let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr + if !bufloaded(bufnr) + return + endif + let src_id = s:create_namespace(a:key) + if has('nvim') + call nvim_buf_clear_namespace(a:bufnr, src_id, a:start_line, a:end_line) + else + call coc#api#call('buf_clear_namespace', [a:bufnr, src_id, a:start_line, a:end_line]) + endif +endfunction + +" highlight buffer in winid with CodeBlock &HighlightItems +" export interface HighlightItem { +" lnum: number // 0 based +" hlGroup: string +" colStart: number // 0 based +" colEnd: number +" } +" export interface CodeBlock { +" filetype?: string +" hlGroup?: string +" startLine: number // 0 based +" endLine: number +" } +function! coc#highlight#add_highlights(winid, codes, highlights) abort + " clear highlights + call coc#compat#execute(a:winid, 'syntax clear') + let bufnr = winbufnr(a:winid) + call coc#highlight#clear_highlight(bufnr, -1, 0, -1) + if !empty(a:codes) + call coc#highlight#highlight_lines(a:winid, a:codes) + endif + if !empty(a:highlights) + for item in a:highlights + call coc#highlight#add_highlight(bufnr, -1, item['hlGroup'], item['lnum'], item['colStart'], item['colEnd']) + endfor + endif +endfunction + + +" Add highlights to line groups of winid, support hlGroup and filetype +" config should have startLine, endLine (1 based, end excluded) and filetype or hlGroup +" endLine should > startLine and endLine is excluded +" +" export interface CodeBlock { +" filetype?: string +" hlGroup?: string +" startLine: number // 0 based +" endLine: number +" } +function! coc#highlight#highlight_lines(winid, blocks) abort + let currwin = win_getid() + let switch = has('nvim') && currwin != a:winid + if switch + noa call nvim_set_current_win(a:winid) + endif + let defined = [] + let region_id = 1 + for config in a:blocks + let start = config['startLine'] + 1 + let end = config['endLine'] == -1 ? len(getbufline(winbufnr(a:winid), 1, '$')) + 1 : config['endLine'] + 1 + let filetype = get(config, 'filetype', '') + let hlGroup = get(config, 'hlGroup', '') + if !empty(hlGroup) + call s:execute(a:winid, 'syntax region '.hlGroup.' start=/\%'.start.'l/ end=/\%'.end.'l/') + else + let filetype = matchstr(filetype, '\v^\w+') + if empty(filetype) || filetype == 'txt' || index(get(g:, 'coc_markdown_disabled_languages', []), filetype) != -1 + continue + endif + if index(defined, filetype) == -1 + call s:execute(a:winid, 'syntax include @'.toupper(filetype).' syntax/'.filetype.'.vim') + if has('nvim') + unlet! b:current_syntax + elseif exists('*win_execute') + call win_execute(a:winid, 'unlet! b:current_syntax') + endif + call add(defined, filetype) + endif + call s:execute(a:winid, 'syntax region CodeBlock'.region_id.' start=/\%'.start.'l/ end=/\%'.end.'l/ contains=@'.toupper(filetype)) + let region_id = region_id + 1 + endif + endfor + if switch + noa call nvim_set_current_win(currwin) + endif +endfunction + +" Copmpose hlGroups with foreground and background colors. +function! coc#highlight#compose_hlgroup(fgGroup, bgGroup) abort + let hlGroup = 'Fg'.a:fgGroup.'Bg'.a:bgGroup + if a:fgGroup == a:bgGroup + return a:fgGroup + endif + if hlexists(hlGroup) + return hlGroup + endif + let fg = synIDattr(synIDtrans(hlID(a:fgGroup)), 'fg', 'gui') + let bg = synIDattr(synIDtrans(hlID(a:bgGroup)), 'bg', 'gui') + if fg =~# '^#' || bg =~# '^#' + call s:create_gui_hlgroup(hlGroup, fg, bg, '') + else + let fg = synIDattr(synIDtrans(hlID(a:fgGroup)), 'fg', 'cterm') + let bg = synIDattr(synIDtrans(hlID(a:bgGroup)), 'bg', 'cterm') + call s:create_cterm_hlgroup(hlGroup, fg, bg, '') + endif + return hlGroup +endfunction + +" add matches for winid, use 0 for current window. +function! coc#highlight#match_ranges(winid, bufnr, ranges, hlGroup, priority) abort + let winid = a:winid == 0 ? win_getid() : a:winid + let bufnr = a:bufnr == 0 ? winbufnr(winid) : a:bufnr + if empty(getwininfo(winid)) || (a:bufnr != 0 && winbufnr(a:winid) != a:bufnr) + " not valid + return [] + endif + if !s:clear_match_by_window + let curr = win_getid() + if has('nvim') + noa call nvim_set_current_win(winid) + else + noa call win_gotoid(winid) + endif + endif + let ids = [] + for range in a:ranges + let list = [] + let start = range['start'] + let end = range['end'] + for lnum in range(start['line'] + 1, end['line'] + 1) + let arr = getbufline(bufnr, lnum) + let line = empty(arr) ? '' : arr[0] + if empty(line) + continue + endif + let colStart = lnum == start['line'] + 1 ? strlen(strcharpart(line, 0, start['character'])) + 1 : 1 + let colEnd = lnum == end['line'] + 1 ? strlen(strcharpart(line, 0, end['character'])) + 1 : strlen(line) + 1 + if colStart == colEnd + continue + endif + call add(list, [lnum, colStart, colEnd - colStart]) + endfor + if !empty(list) + let opts = s:clear_match_by_window ? {'window': a:winid} : {} + let id = matchaddpos(a:hlGroup, list, a:priority, -1, opts) + call add(ids, id) + endif + endfor + if !s:clear_match_by_window + if has('nvim') + noa call nvim_set_current_win(curr) + else + noa call win_gotoid(curr) + endif + endif + return ids +endfunction + +" Clear matches by hlGroup regexp. +function! coc#highlight#clear_match_group(winid, match) abort + let winid = a:winid == 0 ? win_getid() : a:winid + if empty(getwininfo(winid)) + " not valid + return + endif + if s:clear_match_by_window + let arr = filter(getmatches(winid), 'v:val["group"] =~# "'.a:match.'"') + for item in arr + call matchdelete(item['id'], winid) + endfor + else + let curr = win_getid() + let switch = exists('*nvim_set_current_win') && curr != winid + if switch + noa call nvim_set_current_win(a:winid) + endif + if win_getid() == winid + let arr = filter(getmatches(), 'v:val["group"] =~# "'.a:match.'"') + for item in arr + call matchdelete(item['id']) + endfor + endif + if switch + noa call nvim_set_current_win(curr) + endif + endif +endfunction + +" Clear matches by match ids, use 0 for current win. +function! coc#highlight#clear_matches(winid, ids) + let winid = a:winid == 0 ? win_getid() : a:winid + if empty(getwininfo(winid)) + " not valid + return + endif + if s:clear_match_by_window + for id in a:ids + try + call matchdelete(id, winid) + catch /^Vim\%((\a\+)\)\=:E803/ + " ignore + endtry + endfor + else + let curr = win_getid() + let switch = exists('*nvim_set_current_win') && curr != winid + if switch + noa call nvim_set_current_win(a:winid) + endif + if win_getid() == winid + for id in a:ids + try + call matchdelete(id) + catch /^Vim\%((\a\+)\)\=:E803/ + " ignore + endtry + endfor + endif + if switch + noa call nvim_set_current_win(curr) + endif + endif +endfunction + +" Sets the highlighting for the given group +function! s:create_gui_hlgroup(group, fg, bg, attr) + if a:fg != "" + exec "silent hi " . a:group . " guifg=" . a:fg . " ctermfg=" . coc#color#rgb2term(strpart(a:fg, 1)) + endif + if a:bg != "" + exec "silent hi " . a:group . " guibg=" . a:bg . " ctermbg=" . coc#color#rgb2term(strpart(a:bg, 1)) + endif + if a:attr != "" + exec "silent hi " . a:group . " gui=" . a:attr . " cterm=" . a:attr + endif +endfun + +function! s:create_cterm_hlgroup(group, fg, bg, attr) abort + if a:fg != "" + exec "silent hi " . a:group . " ctermfg=" . a:fg + endif + if a:bg != "" + exec "silent hi " . a:group . " ctermbg=" . a:bg + endif + if a:attr != "" + exec "silent hi " . a:group . " cterm=" . a:attr + endif +endfunction + +function! s:execute(winid, cmd) abort + if has('nvim') + execute 'silent! ' a:cmd + else + call win_execute(a:winid, a:cmd, 'silent!') + endif +endfunction + +function! s:create_namespace(key) abort + if type(a:key) == 0 + return a:key + endif + if has('nvim') + return nvim_create_namespace('coc-'.a:key) + endif + if !has_key(s:namespace_map, a:key) + let s:namespace_map[a:key] = s:ns_id + let s:ns_id = s:ns_id + 1 + endif + return s:namespace_map[a:key] +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/list.vim b/pack/acp/opt/coc.nvim/autoload/coc/list.vim index 33eb067..985c26e 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/list.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/list.vim @@ -1,178 +1,31 @@ -let s:activated = 0 let s:is_vim = !has('nvim') -let s:saved_ve = &t_ve -let s:saved_cursor = &guicursor -let s:gui = has('gui_running') || has('nvim') - -function! coc#list#get_chars() - return { - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '' : "\", - \ '' : "\", - \ '' : "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '<2-LeftMouse>': "\<2-LeftMouse>", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \ '': "\", - \} -endfunction - -function! coc#list#getc() abort - let c = getchar() - return type(c) == type(0) ? nr2char(c) : c -endfunction +let s:prefix = '[List Preview]' +" filetype detect could be slow. +let s:filetype_map = { + \ 'vim': 'vim', + \ 'ts': 'typescript', + \ 'js': 'javascript', + \ 'html': 'html', + \ 'css': 'css' + \ } function! coc#list#getchar() abort - let input = coc#list#getc() - if 1 != &iminsert - return input - endif - "a language keymap is activated, so input must be resolved to the mapped values. - let partial_keymap = mapcheck(input, "l") - while partial_keymap !=# "" - let full_keymap = maparg(input, "l") - if full_keymap ==# "" && len(input) >= 3 "HACK: assume there are no keymaps longer than 3. - return input - elseif full_keymap ==# partial_keymap - return full_keymap - endif - let c = coc#list#getc() - if c ==# "\" || c ==# "\" - "if the short sequence has a valid mapping, return that. - if !empty(full_keymap) - return full_keymap - endif - return input - endif - let input .= c - let partial_keymap = mapcheck(input, "l") - endwhile - return input + return coc#prompt#getchar() endfunction -function! coc#list#start_prompt(...) abort - let eventName = get(a:, 1, 'InputChar') - if s:is_vim - call s:start_prompt_vim(eventName) - else - call s:start_prompt(eventName) - endif -endfunction - -function! s:start_prompt_vim(eventName) abort - call timer_start(10, {-> s:start_prompt(a:eventName)}) -endfunction - -function! s:start_prompt(eventName) - if s:activated | return | endif - if !get(g:, 'coc_disable_transparent_cursor', 0) - if s:gui - if has('nvim-0.5.0') && !empty(s:saved_cursor) - set guicursor+=a:ver1-CocCursorTransparent/lCursor - endif - elseif s:is_vim - set t_ve= - endif - endif - let s:activated = 1 - try - while s:activated - let ch = coc#list#getchar() - if ch ==# "\u26d4" - break - endif - if ch ==# "\" || ch ==# "\" || ch ==# "\" - continue - else - call coc#rpc#notify(a:eventName, [ch, getcharmod()]) - endif - endwhile - catch /^Vim:Interrupt$/ - let s:activated = 0 - call coc#rpc#notify(a:eventName, ["\"]) - return - endtry - let s:activated = 0 -endfunction - -function! coc#list#setlines(lines, append) +function! coc#list#setlines(bufnr, lines, append) if a:append - silent call append(line('$'), a:lines) + silent call appendbufline(a:bufnr, '$', a:lines) else - silent call append(0, a:lines) if exists('*deletebufline') - call deletebufline('%', len(a:lines) + 1, '$') + call deletebufline(a:bufnr, len(a:lines) + 1, '$') else let n = len(a:lines) + 1 let saved_reg = @" silent execute n.',$d' let @" = saved_reg endif + silent call setbufline(a:bufnr, 1, a:lines) endif endfunction @@ -192,25 +45,6 @@ function! coc#list#names(...) abort return join(names, "\n") endfunction -function! coc#list#stop_prompt(...) - if s:activated - let s:activated = 0 - if get(a:, 1, 0) == 0 && !get(g:, 'coc_disable_transparent_cursor',0) - " neovim has bug with revert empty &guicursor - if s:gui && !empty(s:saved_cursor) - if has('nvim-0.5.0') - set guicursor+=a:ver1-Cursor/lCursor - let &guicursor = s:saved_cursor - endif - elseif s:is_vim - let &t_ve = s:saved_ve - endif - endif - echo "" - call feedkeys("\u26d4", 'int') - endif -endfunction - function! coc#list#status(name) if !exists('b:list_status') | return '' | endif return get(b:list_status, a:name, '') @@ -264,25 +98,57 @@ function! coc#list#setup(source) nnoremap c endfunction +" Check if previewwindow exists on current tab. function! coc#list#has_preview() for i in range(1, winnr('$')) - let preview = getwinvar(i, '&previewwindow') + let preview = getwinvar(i, 'previewwindow', getwinvar(i, '&previewwindow', 0)) if preview - return 1 + return i endif endfor return 0 endfunction -function! coc#list#restore(winid, height) - let res = win_gotoid(a:winid) - if res == 0 | return | endif - if winnr('$') == 1 +" Get previewwindow from tabnr, use 0 for current tab +function! coc#list#get_preview(...) abort + let tabnr = get(a:, 1, 0) == 0 ? tabpagenr() : a:1 + let info = gettabinfo(tabnr) + if !empty(info) + for win in info[0]['windows'] + if getwinvar(win, 'previewwindow', 0) + return win + endif + endfor + endif + return -1 +endfunction + +function! coc#list#scroll_preview(dir) abort + let winnr = coc#list#has_preview() + if !winnr return endif - execute 'resize '.a:height - if s:is_vim - redraw + let winid = win_getid(winnr) + if exists('*win_execute') + call win_execute(winid, "normal! ".(a:dir ==# 'up' ? "\" : "\")) + else + let id = win_getid() + noa call win_gotoid(winid) + execute "normal! ".(a:dir ==# 'up' ? "\" : "\") + noa call win_gotoid(id) + endif +endfunction + +function! coc#list#restore(winid, height) + if has('nvim') + if nvim_win_is_valid(a:winid) + call nvim_win_set_height(a:winid, a:height) + endif + else + if exists('win_execute') + call win_execute(a:winid, 'noa resize '.a:height, 'silent!') + redraw + endif endif endfunction @@ -290,3 +156,187 @@ function! coc#list#set_height(height) abort if winnr('$') == 1| return | endif execute 'resize '.a:height endfunction + +function! coc#list#hide(original, height, winid) abort + let arr = win_id2tabwin(a:winid) + " close preview window + if !empty(arr) && arr[0] != 0 + silent! pclose! + let previewwin = coc#list#get_preview(arr[0]) + call s:close_win(previewwin) + endif + if !empty(getwininfo(a:original)) + call win_gotoid(a:original) + endif + if a:winid + call s:close_win(a:winid) + endif + if !empty(a:height) && win_getid() == a:original + if exists('*nvim_win_set_height') + call nvim_win_set_height(a:original, a:height) + elseif win_getid() == a:original + execute 'resize '.a:height + endif + endif +endfunction + +function! s:close_win(winid) abort + if empty(a:winid) || a:winid == -1 || empty(getwininfo(a:winid)) + return + endif + if s:is_vim + if exists('*win_execute') + noa call win_execute(a:winid, 'close!', 'silent!') + else + if win_getid() == a:winid + noa silent! close! + else + let winid = win_getid() + let res = win_gotoid(winid) + if res + noa silent! close! + noa wincmd p + endif + endif + endif + else + if nvim_win_is_valid(a:winid) + silent! noa call nvim_win_close(a:winid, 1) + endif + endif +endfunction + +" Improve preview performance by reused window & buffer. +" lines - list of lines +" config.position - could be 'below' 'top' 'tab'. +" config.winid - id of original window. +" config.name - (optional )name of preview buffer. +" config.splitRight - (optional) split to right when 1. +" config.lnum - (optional) current line number +" config.filetype - (optional) filetype of lines. +" config.hlGroup - (optional) highlight group. +" config.maxHeight - (optional) max height of window, valid for 'below' & 'top' position. +function! coc#list#preview(lines, config) abort + if s:is_vim && !exists('*win_execute') + throw 'win_execute function required for preview, please upgrade your vim.' + return + endif + let name = fnamemodify(get(a:config, 'name', ''), ':.') + let lines = a:lines + if empty(lines) + if get(a:config, 'scheme', 'file') != 'file' + let bufnr = s:load_buffer(name) + if bufnr != 0 + let lines = getbufline(bufnr, 1, '$') + else + let lines = [''] + endif + else + " Show empty lines so not close window. + let lines = [''] + endif + endif + let winid = coc#list#get_preview(0) + let bufnr = winid == -1 ? 0 : winbufnr(winid) + " Try reuse buffer & window + let bufnr = coc#float#create_buf(bufnr, lines) + if bufnr == 0 + return + endif + call setbufvar(bufnr, '&synmaxcol', 500) + let filetype = get(a:config, 'filetype', '') + let extname = matchstr(name, '\.\zs[^.]\+$') + if empty(filetype) && !empty(extname) + let filetype = get(s:filetype_map, extname, '') + endif + let range = get(a:config, 'range', v:null) + let hlGroup = get(a:config, 'hlGroup', 'Search') + let lnum = get(a:config, 'lnum', 1) + let position = get(a:config, 'position', 'below') + let original = get(a:config, 'winid', -1) + if winid == -1 + let change = position != 'tab' && get(a:config, 'splitRight', 0) + let curr = win_getid() + if change + if original && win_id2win(original) + noa call win_gotoid(original) + else + noa wincmd t + endif + execute 'noa belowright vert sb '.bufnr + let winid = win_getid() + elseif position == 'tab' || get(a:config, 'splitRight', 0) + execute 'noa belowright vert sb '.bufnr + let winid = win_getid() + else + let mod = position == 'top' ? 'below' : 'above' + let height = s:get_height(lines, a:config) + execute 'noa '.mod.' sb +resize\ '.height.' '.bufnr + let winid = win_getid() + endif + noa call winrestview({"lnum": lnum ,"topline":max([1, lnum - 3])}) + call setwinvar(winid, '&signcolumn', 'no') + call setwinvar(winid, '&number', 1) + call setwinvar(winid, '&cursorline', 0) + call setwinvar(winid, '&relativenumber', 0) + call setwinvar(winid, 'previewwindow', 1) + noa call win_gotoid(curr) + else + let height = s:get_height(lines, a:config) + if height > 0 + if s:is_vim + let curr = win_getid() + noa call win_gotoid(winid) + execute 'silent! noa resize '.height + noa call win_gotoid(curr) + else + call nvim_win_set_height(winid, height) + endif + endif + call coc#compat#execute(winid, ['syntax clear', 'noa call winrestview({"lnum":'.lnum.',"topline":'.max([1, lnum - 3]).'})']) + endif + if s:prefix.' '.name != bufname(bufnr) + if s:is_vim + call win_execute(winid, 'noa file '.fnameescape(s:prefix.' '.name), 'silent!') + else + silent! noa call nvim_buf_set_name(bufnr, s:prefix.' '.name) + endif + endif + " highlights + if !empty(filetype) + let start = max([0, lnum - 300]) + let end = min([len(lines), lnum + 300]) + call coc#highlight#highlight_lines(winid, [{'filetype': filetype, 'startLine': start, 'endLine': end}]) + call coc#compat#execute(winid, 'syn sync fromstart') + else + call coc#compat#execute(winid, 'filetype detect') + let ft = getbufvar(bufnr, '&filetype', '') + if !empty(extname) && !empty(ft) + let s:filetype_map[extname] = ft + endif + endif + call sign_unplace('coc', {'buffer': bufnr}) + call coc#compat#execute(winid, 'call clearmatches()') + if !empty(range) + call sign_place(1, 'coc', 'CocCurrentLine', bufnr, {'lnum': lnum}) + call coc#highlight#match_ranges(winid, bufnr, [range], hlGroup, 10) + endif + redraw +endfunction + +function! s:get_height(lines, config) abort + if get(a:config, 'splitRight', 0) || get(a:config, 'position', 'below') == 'tab' + return 0 + endif + let height = min([get(a:config, 'maxHeight', 10), len(a:lines), &lines - &cmdheight - 2]) + return height +endfunction + +function! s:load_buffer(name) abort + if exists('*bufadd') && exists('*bufload') + let bufnr = bufadd(a:name) + call bufload(bufnr) + return bufnr + endif + return 0 +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/prompt.vim b/pack/acp/opt/coc.nvim/autoload/coc/prompt.vim new file mode 100644 index 0000000..48a315b --- /dev/null +++ b/pack/acp/opt/coc.nvim/autoload/coc/prompt.vim @@ -0,0 +1,208 @@ +let s:is_vim = !has('nvim') +let s:activated = 0 +let s:session_names = [] +let s:saved_ve = &t_ve +let s:saved_cursor = &guicursor +let s:gui = has('gui_running') || has('nvim') + +let s:char_map = { + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\":'' , + \ "\":'' , + \ "\":'' , + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\<2-LeftMouse>": '<2-LeftMouse>', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ "\": '', + \ } + +function! coc#prompt#getc() abort + let c = getchar() + return type(c) == type(0) ? nr2char(c) : c +endfunction + +function! coc#prompt#getchar() abort + let input = coc#prompt#getc() + if 1 != &iminsert + return input + endif + "a language keymap is activated, so input must be resolved to the mapped values. + let partial_keymap = mapcheck(input, "l") + while partial_keymap !=# "" + let full_keymap = maparg(input, "l") + if full_keymap ==# "" && len(input) >= 3 "HACK: assume there are no keymaps longer than 3. + return input + elseif full_keymap ==# partial_keymap + return full_keymap + endif + let c = coc#prompt#getc() + if c ==# "\" || c ==# "\" + "if the short sequence has a valid mapping, return that. + if !empty(full_keymap) + return full_keymap + endif + return input + endif + let input .= c + let partial_keymap = mapcheck(input, "l") + endwhile + return input +endfunction + +function! coc#prompt#start_prompt(session) abort + let s:session_names = s:filter(s:session_names, a:session) + call add(s:session_names, a:session) + if s:activated | return | endif + if s:is_vim + call s:start_prompt_vim() + else + call s:start_prompt() + endif +endfunction + +function! s:start_prompt_vim() abort + call timer_start(10, {-> s:start_prompt()}) +endfunction + +function! s:start_prompt() + if s:activated | return | endif + if !get(g:, 'coc_disable_transparent_cursor', 0) + if s:gui + if has('nvim-0.5.0') && !empty(s:saved_cursor) + set guicursor+=a:ver1-CocCursorTransparent/lCursor + endif + elseif s:is_vim + set t_ve= + endif + endif + let s:activated = 1 + try + while s:activated + let ch = coc#prompt#getchar() + if ch ==# "\" || ch ==# "\" || ch ==# "\" + continue + else + let curr = s:current_session() + let mapped = get(s:char_map, ch, ch) + if !empty(curr) + call coc#rpc#notify('InputChar', [curr, mapped, getcharmod()]) + endif + if mapped == '' + let s:session_names = [] + call s:reset() + break + endif + endif + endwhile + catch /^Vim:Interrupt$/ + let s:activated = 0 + call coc#rpc#notify('InputChar', [s:current_session(), '']) + return + endtry + let s:activated = 0 +endfunction + +function! coc#prompt#stop_prompt(session) + let s:session_names = s:filter(s:session_names, a:session) + if len(s:session_names) + return + endif + if s:activated + let s:activated = 0 + call s:reset() + call feedkeys("\", 'int') + endif +endfunction + +function! coc#prompt#activated() abort + return s:activated +endfunction + +function! s:reset() abort + if !get(g:, 'coc_disable_transparent_cursor',0) + " neovim has bug with revert empty &guicursor + if s:gui && !empty(s:saved_cursor) + if has('nvim-0.5.0') + set guicursor+=a:ver1-Cursor/lCursor + let &guicursor = s:saved_cursor + endif + elseif s:is_vim + let &t_ve = s:saved_ve + endif + endif + echo "" +endfunction + +function! s:current_session() abort + if empty(s:session_names) + return v:null + endif + return s:session_names[len(s:session_names) - 1] +endfunction + +function! s:filter(list, id) abort + return filter(copy(a:list), 'v:val !=# a:id') +endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim b/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim index 659cc11..f08fb2f 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim @@ -117,11 +117,11 @@ endfunction " send async response to server function! coc#rpc#async_request(id, method, args) - let l:Cb = {err, res -> coc#rpc#notify('nvim_async_response_event', [a:id, err, res])} + let l:Cb = {err, ... -> coc#rpc#notify('nvim_async_response_event', [a:id, err, get(a:000, 0, v:null)])} let args = a:args + [l:Cb] try call call(a:method, args) catch /.*/ - call coc#rpc#notify('nvim_async_response_event', [a:id, v:exception]) + call coc#rpc#notify('nvim_async_response_event', [a:id, v:exception, v:null]) endtry endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/task.vim b/pack/acp/opt/coc.nvim/autoload/coc/task.vim index 2ef00a1..ad8ea2e 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/task.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/task.vim @@ -3,11 +3,14 @@ " Author: Qiming Zhao " Licence: MIT licence " Version: 0.1 -" Last Modified: April 08, 2019 +" Last Modified: Dec 12, 2020 " ============================================================================ let s:is_vim = !has('nvim') let s:running_task = {} +" neovim emit strings that part of lines. +let s:out_remain_text = {} +let s:err_remain_text = {} function! coc#task#start(id, opts) if coc#task#running(a:id) @@ -15,6 +18,7 @@ function! coc#task#start(id, opts) endif let cmd = [a:opts['cmd']] + get(a:opts, 'args', []) let cwd = get(a:opts, 'cwd', getcwd()) + let env = get(a:opts, 'env', {}) " cmd args cwd pty if s:is_vim let options = { @@ -24,6 +28,7 @@ function! coc#task#start(id, opts) \ 'err_cb': {channel, message -> s:on_stderr(a:id, [message])}, \ 'out_cb': {channel, message -> s:on_stdout(a:id, [message])}, \ 'exit_cb': {channel, code -> s:on_exit(a:id, code)}, + \ 'env': env, \} if has("patch-8.1.350") let options['noblock'] = 1 @@ -41,15 +46,27 @@ function! coc#task#start(id, opts) else let options = { \ 'cwd': cwd, - \ 'on_stderr': {channel, msgs -> s:on_stderr(a:id, filter(msgs, 'v:val !=""'))}, - \ 'on_stdout': {channel, msgs -> s:on_stdout(a:id, filter(msgs, 'v:val !=""'))}, + \ 'on_stderr': {channel, msgs -> s:on_stderr(a:id, msgs)}, + \ 'on_stdout': {channel, msgs -> s:on_stdout(a:id, msgs)}, \ 'on_exit': {channel, code -> s:on_exit(a:id, code)}, \ 'detach': get(a:opts, 'detach', 0), \} + let original = {} + if !empty(env) && exists('*setenv') && exists('*getenv') + for key in keys(env) + let original[key] = getenv(key) + call setenv(key, env[key]) + endfor + endif if get(a:opts, 'pty', 0) let options['pty'] = 1 endif let chan_id = jobstart(cmd, options) + if !empty(original) + for key in keys(original) + call setenv(key, original[key]) + endfor + endif if chan_id <= 0 echohl Error | echom 'Failed to start '.a:id.' task' | echohl None return v:false @@ -76,6 +93,10 @@ endfunction function! s:on_exit(id, code) abort if get(g:, 'coc_vim_leaving', 0) | return | endif + if has('nvim') + let s:out_remain_text[a:id] = '' + let s:err_remain_text[a:id] = '' + endif if has_key(s:running_task, a:id) call remove(s:running_task, a:id) endif @@ -84,14 +105,58 @@ endfunction function! s:on_stderr(id, msgs) if get(g:, 'coc_vim_leaving', 0) | return | endif - if len(a:msgs) + if empty(a:msgs) + return + endif + if s:is_vim call coc#rpc#notify('TaskStderr', [a:id, a:msgs]) + else + let remain = get(s:err_remain_text, a:id, '') + let eof = (a:msgs == ['']) + let msgs = copy(a:msgs) + if len(remain) > 0 + if msgs[0] == '' + let msgs[0] = remain + else + let msgs[0] = remain . msgs[0] + endif + endif + let last = msgs[len(msgs) - 1] + let s:err_remain_text[a:id] = len(last) > 0 ? last : '' + " all lines from 0 to n - 2 + if len(msgs) > 1 + call coc#rpc#notify('TaskStderr', [a:id, msgs[:len(msgs)-2]]) + elseif eof && len(msgs[0]) > 0 + call coc#rpc#notify('TaskStderr', [a:id, msgs]) + endif endif endfunction function! s:on_stdout(id, msgs) - if len(a:msgs) + if empty(a:msgs) + return + endif + if s:is_vim call coc#rpc#notify('TaskStdout', [a:id, a:msgs]) + else + let remain = get(s:out_remain_text, a:id, '') + let eof = (a:msgs == ['']) + let msgs = copy(a:msgs) + if len(remain) > 0 + if msgs[0] == '' + let msgs[0] = remain + else + let msgs[0] = remain . msgs[0] + endif + endif + let last = msgs[len(msgs) - 1] + let s:out_remain_text[a:id] = len(last) > 0 ? last : '' + " all lines from 0 to n - 2 + if len(msgs) > 1 + call coc#rpc#notify('TaskStdout', [a:id, msgs[:len(msgs)-2]]) + elseif eof && len(msgs[0]) > 0 + call coc#rpc#notify('TaskStdout', [a:id, msgs]) + endif endif endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim b/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim index 24dc0b7..47bd7b0 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim @@ -23,7 +23,7 @@ function! coc#terminal#start(cmd, cwd, env) abort " use env option when possible if s:is_vim let env = copy(a:env) - else + elseif exists('*setenv') for key in keys(a:env) let original[key] = getenv(key) call setenv(key, a:env[key]) @@ -44,7 +44,7 @@ function! coc#terminal#start(cmd, cwd, env) abort \ 'on_exit': {job, status -> s:OnExit(status)}, \ 'env': env, \ }) - if !empty(original) + if !empty(original) && exists('*setenv') for key in keys(original) call setenv(key, original[key]) endfor diff --git a/pack/acp/opt/coc.nvim/autoload/coc/util.vim b/pack/acp/opt/coc.nvim/autoload/coc/util.vim index 6b98f8b..ccf9bc7 100644 --- a/pack/acp/opt/coc.nvim/autoload/coc/util.vim +++ b/pack/acp/opt/coc.nvim/autoload/coc/util.vim @@ -2,6 +2,7 @@ let s:root = expand(':h:h:h') let s:is_win = has('win32') || has('win64') let s:is_vim = !has('nvim') let s:clear_match_by_id = has('nvim-0.5.0') || has('patch-8.1.1084') +let s:vim_api_version = 8 let s:activate = "" let s:quit = "" @@ -26,95 +27,13 @@ function! coc#util#has_preview() return 0 endfunction -function! coc#util#scroll_preview(dir) abort - let winnr = coc#util#has_preview() - if !winnr - return - endif - let winid = win_getid(winnr) - if exists('*win_execute') - call win_execute(winid, "normal! ".(a:dir ==# 'up' ? "\" : "\")) - else - let id = win_getid() - noa call win_gotoid(winid) - execute "normal! ".(a:dir ==# 'up' ? "\" : "\") - noa call win_gotoid(id) - endif -endfunction - -function! coc#util#has_float() - echohl Error | echon 'coc#util#has_float is deprecated, use coc#float#has_float instead' | echohl None - return coc#float#has_float() -endfunction - -function! coc#util#float_hide() - echohl Error | echon 'coc#util#float_hide is deprecated, use coc#float#close_all instead' | echohl None - call coc#float#close_all() -endfunction - -function! coc#util#float_jump() - echohl Error | echon 'coc#util#float_jump is deprecated, use coc#float#jump instead' | echohl None -endfunction - -" close all float/popup window -function! coc#util#close_floats() abort - echohl WarningMsg | echon 'coc#util#close_floats is deprecated, use coc#float#close_all instead' | echohl None - call coc#float#close_all() -endfunction - -function! coc#util#close_win(id) - echohl WarningMsg | echon 'coc#util#close_win is deprecated, use coc#float#close instead' | echohl None - call coc#float#close(a:id) -endfunction - -function! coc#util#float_scroll(forward) - echohl WarningMsg | echon 'coc#util#close_win is deprecated, use coc#float#scroll instead' | echohl None - call coc#float#scroll(a:forward) -endfunction - -" scroll float without exiting insert mode (nvim only) -function! coc#util#float_scroll_i(amount) - let float = coc#float#get_float_win() - if !float | return '' | endif - let buf = nvim_win_get_buf(float) - let buf_height = nvim_buf_line_count(buf) - let win_height = nvim_win_get_height(float) - if buf_height < win_height | return '' | endif - let pos = nvim_win_get_cursor(float) - try - let last_amount = nvim_win_get_var(float, 'coc_float_scroll_last_amount') - catch - let last_amount = 0 - endtry - if a:amount > 0 - if pos[0] == 1 - let pos[0] += a:amount + win_height - 2 - elseif last_amount > 0 - let pos[0] += a:amount - else - let pos[0] += a:amount + win_height - 3 - endif - let pos[0] = pos[0] < buf_height ? pos[0] : buf_height - elseif a:amount < 0 - if pos[0] == buf_height - let pos[0] += a:amount - win_height + 2 - elseif last_amount < 0 - let pos[0] += a:amount - else - let pos[0] += a:amount - win_height + 3 - endif - let pos[0] = pos[0] > 1 ? pos[0] : 1 - endif - call nvim_win_set_var(float, 'coc_float_scroll_last_amount', a:amount) - call nvim_win_set_cursor(float, pos) - return '' +function! coc#util#api_version() abort + return s:vim_api_version endfunction " get cursor position function! coc#util#cursor() - let pos = getcurpos() - let content = pos[2] == 1 ? '' : getline('.')[0: pos[2] - 2] - return [pos[1] - 1, strchars(content)] + return [line('.') - 1, strchars(strpart(getline('.'), 0, col('.') - 1))] endfunction function! coc#util#path_replace_patterns() abort @@ -178,20 +97,11 @@ function! coc#util#job_command() echohl Error | echom '[coc.nvim] "'.node.'" is not executable, checkout https://nodejs.org/en/download/' | echohl None return endif - if filereadable(s:root.'/bin/server.js') && filereadable(s:root.'/src/index.ts') && !get(g:, 'coc_force_bundle', 0) - if !filereadable(s:root.'/lib/attach.js') - echohl Error | echom '[coc.nvim] javascript bundle not found, please try :call coc#util#install()' | echohl None - return - endif - "use javascript from lib - return [node] + get(g:, 'coc_node_args', ['--no-warnings']) + [s:root.'/bin/server.js'] - else - if !filereadable(s:root.'/build/index.js') - echohl Error | echom '[coc.nvim] build/index.js not found, reinstall coc.nvim to fix it.' | echohl None - return - endif - return [node] + get(g:, 'coc_node_args', ['--no-warnings']) + [s:root.'/build/index.js'] + if !filereadable(s:root.'/build/index.js') + echohl Error | echom '[coc.nvim] build/index.js not found, please compile the code by esbuild.' | echohl None + return endif + return [node] + get(g:, 'coc_node_args', ['--no-warnings']) + [s:root.'/build/index.js'] endfunction function! coc#util#echo_hover(msg) @@ -212,13 +122,21 @@ function! coc#util#execute(cmd) endfunction function! coc#util#jump(cmd, filepath, ...) abort - silent! normal! m' + if a:cmd != 'pedit' + silent! normal! m' + endif let path = a:filepath if (has('win32unix')) let path = substitute(a:filepath, '\v\\', '/', 'g') endif let file = fnamemodify(path, ":~:.") - exe a:cmd.' '.fnameescape(file) + if a:cmd == 'pedit' + let extra = empty(get(a:, 1, [])) ? '' : '+'.(a:1[0] + 1) + exe 'pedit '.extra.' '.fnameescape(file) + return + else + exe a:cmd.' '.fnameescape(file) + endif if !empty(get(a:, 1, [])) let line = getline(a:1[0] + 1) " TODO need to use utf16 here @@ -243,6 +161,13 @@ function! coc#util#jumpTo(line, character) abort call cursor(a:line + 1, col) endfunction +" Position of cursor relative to screen cell +function! coc#util#cursor_pos() abort + let nr = winnr() + let [row, col] = win_screenpos(nr) + return [row + winline() - 2, col + wincol() - 2] +endfunction + function! coc#util#echo_messages(hl, msgs) if a:hl !~# 'Error' && (mode() !~# '\v^(i|n)$') return @@ -275,7 +200,7 @@ function! s:Call(method, args) endtry endfunction -function! coc#util#get_bufoptions(bufnr) abort +function! coc#util#get_bufoptions(bufnr, maxFileSize) abort if !bufloaded(a:bufnr) | return v:null | endif let bufname = bufname(a:bufnr) let buftype = getbufvar(a:bufnr, '&buftype') @@ -290,24 +215,29 @@ function! coc#util#get_bufoptions(bufnr) abort elseif !empty(bufname) let size = getfsize(bufname) endif + let lines = [] + if getbufvar(a:bufnr, 'coc_enabled', 1) && (buftype == '' || buftype == 'acwrite') && size < a:maxFileSize + let lines = getbufline(a:bufnr, 1, '$') + endif return { \ 'bufname': bufname, \ 'size': size, - \ 'eol': getbufvar(a:bufnr, '&eol'), \ 'buftype': buftype, \ 'winid': winid, \ 'previewwindow': previewwindow == 0 ? v:false : v:true, \ 'variables': s:variables(a:bufnr), \ 'fullpath': empty(bufname) ? '' : fnamemodify(bufname, ':p'), + \ 'eol': getbufvar(a:bufnr, '&eol'), \ 'filetype': getbufvar(a:bufnr, '&filetype'), \ 'iskeyword': getbufvar(a:bufnr, '&iskeyword'), \ 'changedtick': getbufvar(a:bufnr, 'changedtick'), + \ 'lines': lines, \} endfunction function! s:variables(bufnr) abort - let info = getbufinfo({'bufnr':a:bufnr, 'variables': 1}) - let variables = copy(info[0]['variables']) + let info = getbufinfo(a:bufnr) + let variables = empty(info) ? {} : copy(info[0]['variables']) for key in keys(variables) if key !~# '\v^coc' unlet variables[key] @@ -392,13 +322,11 @@ function! coc#util#get_data_home() endfunction function! coc#util#get_input() - let pos = getcurpos() - let line = getline('.') - let l:start = pos[2] - 1 - while l:start > 0 && line[l:start - 1] =~# '\k' - let l:start -= 1 - endwhile - return pos[2] == 1 ? '' : line[l:start : pos[2] - 2] + let before = strpart(getline('.'), 0, col('.')-1) + if len(before) == 0 + return '' + endif + return matchstr(before, '\k*$') endfunction function! coc#util#move_cursor(delta) @@ -407,26 +335,13 @@ function! coc#util#move_cursor(delta) endfunction function! coc#util#get_complete_option() - let disabled = get(b:, 'coc_suggest_disable', 0) - if disabled | return | endif - let blacklist = get(b:, 'coc_suggest_blacklist', []) let pos = getcurpos() - let l:start = pos[2] - 1 let line = getline(pos[1]) - for char in reverse(split(line[0: l:start - 1], '\zs')) - if l:start > 0 && char =~# '\k' - let l:start = l:start - strlen(char) - else - break - endif - endfor - let input = pos[2] == 1 ? '' : line[l:start : pos[2] - 2] - if !empty(blacklist) && index(blacklist, input) >= 0 - return - endif - let synname = synIDattr(synID(pos[1], l:start, 1),"name") + let input = matchstr(strpart(line, 0, pos[2] - 1), '\k*$') + let col = pos[2] - strlen(input) + let synname = synIDattr(synID(pos[1], col, 1), 'name') return { - \ 'word': matchstr(line[l:start : ], '^\k\+'), + \ 'word': matchstr(strpart(line, col - 1), '^\k\+'), \ 'input': empty(input) ? '' : input, \ 'line': line, \ 'filetype': &filetype, @@ -434,10 +349,10 @@ function! coc#util#get_complete_option() \ 'bufnr': bufnr('%'), \ 'linenr': pos[1], \ 'colnr' : pos[2], - \ 'col': l:start, + \ 'col': col - 1, \ 'synname': synname, \ 'changedtick': b:changedtick, - \ 'blacklist': blacklist, + \ 'blacklist': get(b:, 'coc_suggest_blacklist', []), \} endfunction @@ -475,6 +390,7 @@ function! coc#util#quickpick(title, items, cb) abort \ 'filter': function('s:QuickpickFilter'), \ 'callback': function('s:QuickpickHandler'), \ }) + redraw catch /.*/ call a:cb(v:exception) endtry @@ -484,55 +400,6 @@ function! coc#util#quickpick(title, items, cb) abort endif endfunction -function! coc#util#prompt(title, cb) abort - if exists('*popup_dialog') - function! s:PromptHandler(id, result) closure - call a:cb(v:null, a:result) - endfunction - try - call popup_dialog(a:title. ' (y/n)', #{ - \ filter: 'popup_filter_yesno', - \ callback: function('s:PromptHandler'), - \ }) - catch /.*/ - call a:cb(v:exception) - endtry - elseif !s:is_vim && exists('*confirm') - let choice = confirm(a:title, "&Yes\n&No") - call a:cb(v:null, choice == 1) - else - echohl MoreMsg - echom a:title.' (y/n)' - echohl None - let confirm = nr2char(getchar()) - redraw! - if !(confirm ==? "y" || confirm ==? "\r") - echohl Moremsg | echo 'Cancelled.' | echohl None - return 0 - call a:cb(v:null, 0) - end - call a:cb(v:null, 1) - endif -endfunction - -function! coc#util#prompt_confirm(title) - if exists('*confirm') && !s:is_vim - let choice = confirm(a:title, "&Yes\n&No") - return choice == 1 - else - echohl MoreMsg - echom a:title.' (y/n)' - echohl None - let confirm = nr2char(getchar()) - redraw! - if !(confirm ==? "y" || confirm ==? "\r") - echohl Moremsg | echo 'Cancelled.' | echohl None - return 0 - end - return 1 - endif -endfunction - function! coc#util#get_syntax_name(lnum, col) return synIDattr(synIDtrans(synID(a:lnum,a:col,1)),"name") endfunction @@ -654,10 +521,10 @@ endfunction function! coc#util#vim_info() return { + \ 'apiversion': s:vim_api_version, \ 'mode': mode(), \ 'floating': has('nvim') && exists('*nvim_open_win') ? v:true : v:false, \ 'extensionRoot': coc#util#extension_root(), - \ 'watchExtensions': get(g:, 'coc_watch_extensions', []), \ 'globalExtensions': get(g:, 'coc_global_extensions', []), \ 'config': get(g:, 'coc_user_config', {}), \ 'pid': coc#util#getpid(), @@ -680,7 +547,9 @@ function! coc#util#vim_info() \ 'progpath': v:progpath, \ 'guicursor': &guicursor, \ 'vimCommands': get(g:, 'coc_vim_commands', []), + \ 'sign': exists('*sign_place') && exists('*sign_unplace'), \ 'textprop': has('textprop') && has('patch-8.1.1719') && !has('nvim') ? v:true : v:false, + \ 'dialog': has('nvim-0.4.0') || has('patch-8.2.0750') ? v:true : v:false, \ 'disabledSources': get(g:, 'coc_sources_disable_map', {}), \} endfunction @@ -693,11 +562,53 @@ function! coc#util#highlight_options() \} endfunction -" used by vim -function! coc#util#get_content(bufnr) - if !bufloaded(a:bufnr) | return '' | endif +function! coc#util#set_lines(bufnr, replacement, start, end) abort + if !s:is_vim + call nvim_buf_set_lines(a:bufnr, a:start, a:end, 0, a:replacement) + else + call coc#api#notify('buf_set_lines', [a:bufnr, a:start, a:end, 0, a:replacement]) + endif return { - \ 'content': join(getbufline(a:bufnr, 1, '$'), "\n"), + \ 'lines': getbufline(a:bufnr, 1, '$'), + \ 'changedtick': getbufvar(a:bufnr, 'changedtick') + \ } +endfunction + +function! coc#util#change_lines(bufnr, list) abort + if !bufloaded(a:bufnr) | return v:null | endif + undojoin + if exists('*setbufline') + for [lnum, line] in a:list + call setbufline(a:bufnr, lnum + 1, line) + endfor + elseif a:bufnr == bufnr('%') + for [lnum, line] in a:list + call setline(lnum + 1, line) + endfor + else + let bufnr = bufnr('%') + exe 'noa buffer '.a:bufnr + for [lnum, line] in a:list + call setline(lnum + 1, line) + endfor + exe 'noa buffer '.bufnr + endif + return { + \ 'lines': getbufline(a:bufnr, 1, '$'), + \ 'changedtick': getbufvar(a:bufnr, 'changedtick') + \ } +endfunction + + +" used by vim +function! coc#util#get_buf_lines(bufnr, changedtick) + if !bufloaded(a:bufnr) | return '' | endif + let changedtick = getbufvar(a:bufnr, 'changedtick') + if changedtick == a:changedtick + return v:null + endif + return { + \ 'lines': getbufline(a:bufnr, 1, '$'), \ 'changedtick': getbufvar(a:bufnr, 'changedtick') \ } endfunction @@ -758,9 +669,10 @@ function! coc#util#open_url(url) endfunction function! coc#util#install() abort + let yarncmd = get(g:, 'coc_install_yarn_cmd', executable('yarnpkg') ? 'yarnpkg' : 'yarn') call coc#util#open_terminal({ \ 'cwd': s:root, - \ 'cmd': 'yarn install --frozen-lockfile', + \ 'cmd': yarncmd.' install --frozen-lockfile --ignore-engines', \ 'autoclose': 0, \ }) endfunction @@ -940,26 +852,6 @@ function! coc#util#set_buf_var(bufnr, name, val) abort call setbufvar(a:bufnr, a:name, a:val) endfunction -function! coc#util#change_lines(bufnr, list) abort - if !bufloaded(a:bufnr) | return | endif - if exists('*setbufline') - for [lnum, line] in a:list - call setbufline(a:bufnr, lnum + 1, line) - endfor - elseif a:bufnr == bufnr('%') - for [lnum, line] in a:list - call setline(lnum + 1, line) - endfor - else - let bufnr = bufnr('%') - exe 'noa buffer '.a:bufnr - for [lnum, line] in a:list - call setline(lnum + 1, line) - endfor - exe 'noa buffer '.bufnr - endif -endfunction - function! coc#util#unmap(bufnr, keys) abort if bufnr('%') == a:bufnr for key in a:keys @@ -973,6 +865,7 @@ function! coc#util#open_files(files) " added on latest vim8 if exists('*bufadd') && exists('*bufload') for file in a:files + let file = fnamemodify(file, ':.') if bufloaded(file) call add(bufnrs, bufnr(file)) else @@ -985,6 +878,7 @@ function! coc#util#open_files(files) else noa keepalt 1new +setl\ bufhidden=wipe for file in a:files + let file = fnamemodify(file, ':.') execute 'noa edit +setl\ bufhidden=hide '.fnameescape(file) if &filetype ==# '' filetype detect @@ -1037,67 +931,23 @@ function! coc#util#get_format_opts(bufnr) abort return [tabsize, &expandtab] endfunction -function! coc#util#clear_pos_matches(match, ...) abort - let winid = get(a:, 1, win_getid()) - if empty(getwininfo(winid)) - " not valid - return - endif - if win_getid() == winid - let arr = filter(getmatches(), 'v:val["group"] =~# "'.a:match.'"') - for item in arr - call matchdelete(item['id']) - endfor - elseif s:clear_match_by_id - let arr = filter(getmatches(winid), 'v:val["group"] =~# "'.a:match.'"') - for item in arr - call matchdelete(item['id'], winid) - endfor - endif -endfunction - function! coc#util#clearmatches(ids, ...) let winid = get(a:, 1, win_getid()) - if empty(getwininfo(winid)) - return - endif - if win_getid() == winid - for id in a:ids - try - call matchdelete(id) - catch /.*/ - " matches have been cleared in other ways, - endtry - endfor - elseif s:clear_match_by_id - for id in a:ids - try - call matchdelete(id, winid) - catch /.*/ - " matches have been cleared in other ways, - endtry - endfor - endif + call coc#highlight#clear_matches(winid, a:ids) endfunction -" clear document highlights of current window -function! coc#util#clear_highlights(...) abort - let winid = get(a:, 1, win_getid()) - if empty(getwininfo(winid)) - " not valid - return - endif - if winid == win_getid() - let arr = filter(getmatches(), 'v:val["group"] =~# "^CocHighlight"') - for item in arr - call matchdelete(item['id']) - endfor - elseif s:clear_match_by_id - let arr = filter(getmatches(winid), 'v:val["group"] =~# "^CocHighlight"') - for item in arr - call matchdelete(item['id'], winid) - endfor +" Character offset of current cursor +function! coc#util#get_offset() abort + let offset = 0 + let lnum = line('.') + for i in range(1, lnum) + if i == lnum + let offset += strchars(strpart(getline('.'), 0, col('.')-1)) + else + let offset += strchars(getline(i)) + 1 endif + endfor + return offset endfunction " Make sure window exists @@ -1107,11 +957,3 @@ function! coc#util#win_gotoid(winid) abort throw 'Invalid window number' endif endfunction - -" Make sure pum is visible -function! coc#util#pumvisible() abort - let visible = pumvisible() - if !visible - throw 'Pum not visible' - endif -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/health/coc.vim b/pack/acp/opt/coc.nvim/autoload/health/coc.vim index fe789b9..b79f0e2 100644 --- a/pack/acp/opt/coc.nvim/autoload/health/coc.vim +++ b/pack/acp/opt/coc.nvim/autoload/health/coc.vim @@ -41,20 +41,11 @@ function! s:checkEnvironment() abort endfunction function! s:checkCommand() - let file = s:root.'/bin/server.js' + let file = s:root.'/build/index.js' if filereadable(file) - if !filereadable(s:root.'/lib/attach.js') - call health#report_error('Javascript entry not found, run "yarn install --frozen-lockfile" in terminal to fix it.') - else - call health#report_ok('Javascript entry lib/attach.js found') - endif + call health#report_ok('Javascript bundle build/index.js found') else - let file = s:root.'/build/index.js' - if filereadable(file) - call health#report_ok('Javascript bundle build/index.js found') - else - call health#report_error('Javascript entry not found, reinstall coc.nvim to fix it.') - endif + call health#report_error('Javascript entry not found, please compile coc.nvim by esbuild.') endif endfunction diff --git a/pack/acp/opt/coc.nvim/bin/prompt.js b/pack/acp/opt/coc.nvim/bin/prompt.js new file mode 100644 index 0000000..2361a58 --- /dev/null +++ b/pack/acp/opt/coc.nvim/bin/prompt.js @@ -0,0 +1,73 @@ +/* + * Used for prompt popup on vim + */ +const readline = require("readline") +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + escapeCodeTimeout: 0 +}) +rl.setPrompt('') +let value = process.argv[2] +if (value) { + rl.write(value) +} +rl.on('line', input => { + let text = input.replace(/"/g, '\\"') + console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['confirm', text]]))) + process.exit() +}) + +function createSequences(str) { + return '\033]51;' + str + '\x07' +} + +process.stdin.on('keypress', (_, key) => { + if (key) { + let k = getKey(key) + if (k == '') { + return + } + if (k == '') { + process.exit() + return + } + if (k == '') { + console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['exit', '']]))) + process.exit() + return + } + if (k) { + console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['send', k]]))) + } + } +}) + +function getKey(key) { + if (key.sequence == '\u001b') { + return '' + } + if (key.sequence == '\r') { + return '' + } + if (key.sequence == '\t') { + return key.shift ? '' : '' + } + // handle them can cause bug with terminal + // if (key.name == 'backspace') { + // return '' + // } + // if (key.name == 'left') { + // return '' + // } + // if (key.name == 'right') { + // return '' + // } + if (key.name == 'up') { + return '' + } + if (key.name == 'down') { + return '' + } + return '' +} diff --git a/pack/acp/opt/coc.nvim/terminateProcess.sh b/pack/acp/opt/coc.nvim/bin/terminateProcess.sh old mode 100644 new mode 100755 similarity index 100% rename from pack/acp/opt/coc.nvim/terminateProcess.sh rename to pack/acp/opt/coc.nvim/bin/terminateProcess.sh diff --git a/pack/acp/opt/coc.nvim/build/index.js b/pack/acp/opt/coc.nvim/build/index.js index 5356fce..8e0985a 100644 --- a/pack/acp/opt/coc.nvim/build/index.js +++ b/pack/acp/opt/coc.nvim/build/index.js @@ -1,47040 +1,251 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -const semver = __webpack_require__(1) -const version = process.version.replace('v', '') -const promiseFinally = __webpack_require__(44) -if (!semver.gte(version, '8.10.0')) { - console.error('node version ' + version + ' < 8.10.0, please upgrade nodejs, or use `let g:coc_node_path = "/path/to/node"` in your vimrc') - process.exit() -} -if (!semver.gte(version, '10.12.0')) { - if (process.env.COC_NO_WARNINGS != '1') { - console.error('node version ' + version + ' < 10.12.0, upgrade nodejs or use `let g:coc_disable_startup_warning = 1` to disable this warning.') - } -} -Object.defineProperty(console, 'log', { - value: function () { - logger.info(...arguments) - } -}) -promiseFinally.shim() -const logger = __webpack_require__(64)('server') -const attach = __webpack_require__(154).default - -attach({reader: process.stdin, writer: process.stdout}) - -process.on('uncaughtException', function (err) { - let msg = 'Uncaught exception: ' + err.message - console.error(msg) - logger.error('uncaughtException', err.stack) -}) - -process.on('unhandledRejection', function (reason, p) { - if (reason instanceof Error) { - console.error('UnhandledRejection: ' + reason.message + '\n' + reason.stack) - } else { - console.error('UnhandledRejection: ' + reason) - } - logger.error('unhandledRejection ', p, reason) -}) - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -// just pre-load all the stuff that index.js lazily exports -const internalRe = __webpack_require__(2) -module.exports = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: __webpack_require__(3).SEMVER_SPEC_VERSION, - SemVer: __webpack_require__(5), - compareIdentifiers: __webpack_require__(6).compareIdentifiers, - rcompareIdentifiers: __webpack_require__(6).rcompareIdentifiers, - parse: __webpack_require__(7), - valid: __webpack_require__(8), - clean: __webpack_require__(9), - inc: __webpack_require__(10), - diff: __webpack_require__(11), - major: __webpack_require__(14), - minor: __webpack_require__(15), - patch: __webpack_require__(16), - prerelease: __webpack_require__(17), - compare: __webpack_require__(13), - rcompare: __webpack_require__(18), - compareLoose: __webpack_require__(19), - compareBuild: __webpack_require__(20), - sort: __webpack_require__(21), - rsort: __webpack_require__(22), - gt: __webpack_require__(23), - lt: __webpack_require__(24), - eq: __webpack_require__(12), - neq: __webpack_require__(25), - gte: __webpack_require__(26), - lte: __webpack_require__(27), - cmp: __webpack_require__(28), - coerce: __webpack_require__(29), - Comparator: __webpack_require__(30), - Range: __webpack_require__(31), - satisfies: __webpack_require__(32), - toComparators: __webpack_require__(33), - maxSatisfying: __webpack_require__(34), - minSatisfying: __webpack_require__(35), - minVersion: __webpack_require__(36), - validRange: __webpack_require__(37), - outside: __webpack_require__(38), - gtr: __webpack_require__(39), - ltr: __webpack_require__(40), - intersects: __webpack_require__(41), - simplifyRange: __webpack_require__(42), - subset: __webpack_require__(43), -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(3) -const debug = __webpack_require__(4) -exports = module.exports = {} - -// The actual regexps go on exports.re -const re = exports.re = [] -const src = exports.src = [] -const t = exports.t = {} -let R = 0 - -const createToken = (name, value, isGlobal) => { - const index = R++ - debug(index, value) - t[name] = index - src[index] = value - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) -} - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') - -// ## Main Version -// Three dot-separated numeric identifiers. - -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) - -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`) - -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`) - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) - -createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) - -createToken('FULL', `^${src[t.FULLPLAIN]}$`) - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) - -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) - -createToken('GTLT', '((?:<|>)?=?)') - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) - -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') - -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' - -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') - -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' - -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) - -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) - -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') -// >=0.0.0 is like a star -createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$') -createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$') - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' - -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 - -module.exports = { - SEMVER_SPEC_VERSION, - MAX_LENGTH, - MAX_SAFE_INTEGER, - MAX_SAFE_COMPONENT_LENGTH -} - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} - -module.exports = debug - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(4) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(3) -const { re, t } = __webpack_require__(2) - -const { compareIdentifiers } = __webpack_require__(6) -class SemVer { - constructor (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease - - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format() - this.raw = this.version - return this - } -} - -module.exports = SemVer - - -/***/ }), -/* 6 */ -/***/ (function(module, exports) { - -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - const anum = numeric.test(a) - const bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - -module.exports = { - compareIdentifiers, - rcompareIdentifiers -} - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -const {MAX_LENGTH} = __webpack_require__(3) -const { re, t } = __webpack_require__(2) -const SemVer = __webpack_require__(5) - -const parse = (version, options) => { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re[t.LOOSE] : re[t.FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -module.exports = parse - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -const parse = __webpack_require__(7) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null -} -module.exports = valid - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -const parse = __webpack_require__(7) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) - -const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options - options = undefined - } - - try { - return new SemVer(version, options).inc(release, identifier).version - } catch (er) { - return null - } -} -module.exports = inc - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -const parse = __webpack_require__(7) -const eq = __webpack_require__(12) - -const diff = (version1, version2) => { - if (eq(version1, version2)) { - return null - } else { - const v1 = parse(version1) - const v2 = parse(version2) - const hasPre = v1.prerelease.length || v2.prerelease.length - const prefix = hasPre ? 'pre' : '' - const defaultResult = hasPre ? 'prerelease' : '' - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} -module.exports = diff - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) - -module.exports = compare - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -const parse = __webpack_require__(7) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -module.exports = prerelease - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild - - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -const compareBuild = __webpack_require__(20) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort - - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -const compareBuild = __webpack_require__(20) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -const compare = __webpack_require__(13) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -const eq = __webpack_require__(12) -const neq = __webpack_require__(25) -const gt = __webpack_require__(23) -const gte = __webpack_require__(26) -const lt = __webpack_require__(24) -const lte = __webpack_require__(27) - -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } -} -module.exports = cmp - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const parse = __webpack_require__(7) -const {re, t} = __webpack_require__(2) - -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - let match = null - if (!options.rtl) { - match = version.match(re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next - while ((next = re[t.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - re[t.COERCERTL].lastIndex = -1 - } - - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) -} -module.exports = coerce - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY - } - constructor (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - const sameSemVer = this.semver.version === comp.semver.version - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<') - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>') - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } -} - -module.exports = Comparator - -const {re, t} = __webpack_require__(2) -const cmp = __webpack_require__(28) -const debug = __webpack_require__(4) -const SemVer = __webpack_require__(5) -const Range = __webpack_require__(31) - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.format() - return this - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - this.format() - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim() - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - const loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[t.COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - return range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator(comp, this.options)) - } - - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } -} -module.exports = Range - -const Comparator = __webpack_require__(30) -const debug = __webpack_require__(4) -const SemVer = __webpack_require__(5) -const { - re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace -} = __webpack_require__(2) - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' ') - -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' ') - -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } - } - - debug('caret return', ret) - return ret - }) -} - -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') -} - -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - if (gtlt === '<') - pr = '-0' - - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[t.STAR], '') -} - -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp.trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} - -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` - } - - return (`${from} ${to}`).trim() -} - -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -const Range = __webpack_require__(31) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} -module.exports = satisfies - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -const Range = __webpack_require__(31) - -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) - -module.exports = toComparators - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const Range = __webpack_require__(31) - -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -module.exports = maxSatisfying - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const Range = __webpack_require__(31) -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} -module.exports = minSatisfying - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const Range = __webpack_require__(31) -const gt = __webpack_require__(23) - -const minVersion = (range, loose) => { - range = new Range(range, loose) - - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} -module.exports = minVersion - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -const Range = __webpack_require__(31) -const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -module.exports = validRange - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -const SemVer = __webpack_require__(5) -const Comparator = __webpack_require__(30) -const {ANY} = Comparator -const Range = __webpack_require__(31) -const satisfies = __webpack_require__(32) -const gt = __webpack_require__(23) -const lt = __webpack_require__(24) -const lte = __webpack_require__(27) -const gte = __webpack_require__(26) - -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) - - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let high = null - let low = null - - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -module.exports = outside - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -// Determine if version is greater than all the versions possible in the range. -const outside = __webpack_require__(38) -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -const outside = __webpack_require__(38) -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -const Range = __webpack_require__(31) -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} -module.exports = intersects - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -// given a set of versions and a range, create a "simplified" range -// that includes the same versions that the original range does -// If the original range is shorter than the simplified one, return that. -const satisfies = __webpack_require__(32) -const compare = __webpack_require__(13) -module.exports = (versions, range, options) => { - const set = [] - let min = null - let prev = null - const v = versions.sort((a, b) => compare(a, b, options)) - for (const version of v) { - const included = satisfies(version, range, options) - if (included) { - prev = version - if (!min) - min = version - } else { - if (prev) { - set.push([min, prev]) - } - prev = null - min = null - } - } - if (min) - set.push([min, null]) - - const ranges = [] - for (const [min, max] of set) { - if (min === max) - ranges.push(min) - else if (!max && min === v[0]) - ranges.push('*') - else if (!max) - ranges.push(`>=${min}`) - else if (min === v[0]) - ranges.push(`<=${max}`) - else - ranges.push(`${min} - ${max}`) - } - const simplified = ranges.join(' || ') - const original = typeof range.raw === 'string' ? range.raw : String(range) - return simplified.length < original.length ? simplified : range -} - - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -const Range = __webpack_require__(31) -const { ANY } = __webpack_require__(30) -const satisfies = __webpack_require__(32) -const compare = __webpack_require__(13) - -// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: -// - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...` -// -// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: -// - If c is only the ANY comparator -// - If C is only the ANY comparator, return true -// - Else return false -// - Let EQ be the set of = comparators in c -// - If EQ is more than one, return true (null set) -// - Let GT be the highest > or >= comparator in c -// - Let LT be the lowest < or <= comparator in c -// - If GT and LT, and GT.semver > LT.semver, return true (null set) -// - If EQ -// - If GT, and EQ does not satisfy GT, return true (null set) -// - If LT, and EQ does not satisfy LT, return true (null set) -// - If EQ satisfies every C, return true -// - Else return false -// - If GT -// - If GT is lower than any > or >= comp in C, return false -// - If GT is >=, and GT.semver does not satisfy every C, return false -// - If LT -// - If LT.semver is greater than that of any > comp in C, return false -// - If LT is <=, and LT.semver does not satisfy every C, return false -// - If any C is a = range, and GT or LT are set, return false -// - Else return true - -const subset = (sub, dom, options) => { - sub = new Range(sub, options) - dom = new Range(dom, options) - let sawNonNull = false - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options) - sawNonNull = sawNonNull || isSub !== null - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true -} - -const simpleSubset = (sub, dom, options) => { - if (sub.length === 1 && sub[0].semver === ANY) - return dom.length === 1 && dom[0].semver === ANY - - const eqSet = new Set() - let gt, lt - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options) - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options) - else - eqSet.add(c.semver) - } - - if (eqSet.size > 1) - return null - - let gtltComp - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options) - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false - } - return true - } - - let higher, lower - let hasDomLT, hasDomGT - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' - if (gt) { - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options) - if (higher === c) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options) - if (lower === c) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - return true -} - -// >=1.2.3 is lower than >1.2.3 -const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options) - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a -} - -// <=1.2.3 is higher than <1.2.3 -const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options) - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a -} - -module.exports = subset - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var bind = __webpack_require__(45); -var define = __webpack_require__(47); - -var implementation = __webpack_require__(51); -var getPolyfill = __webpack_require__(62); -var shim = __webpack_require__(63); - -var bound = bind.call(Function.call, getPolyfill()); - -define(bound, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = bound; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var implementation = __webpack_require__(46); - -module.exports = Function.prototype.bind || implementation; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var keys = __webpack_require__(48); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -var toStr = Object.prototype.toString; -var concat = Array.prototype.concat; -var origDefineProperty = Object.defineProperty; - -var isFunction = function (fn) { - return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; -}; - -var arePropertyDescriptorsSupported = function () { - var obj = {}; - try { - origDefineProperty(obj, 'x', { enumerable: false, value: obj }); - // eslint-disable-next-line no-unused-vars, no-restricted-syntax - for (var _ in obj) { // jscs:ignore disallowUnusedVariables - return false; - } - return obj.x === obj; - } catch (e) { /* this is IE 8. */ - return false; - } -}; -var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); - -var defineProperty = function (object, name, value, predicate) { - if (name in object && (!isFunction(predicate) || !predicate())) { - return; - } - if (supportsDescriptors) { - origDefineProperty(object, name, { - configurable: true, - enumerable: false, - value: value, - writable: true - }); - } else { - object[name] = value; - } -}; - -var defineProperties = function (object, map) { - var predicates = arguments.length > 2 ? arguments[2] : {}; - var props = keys(map); - if (hasSymbols) { - props = concat.call(props, Object.getOwnPropertySymbols(map)); - } - for (var i = 0; i < props.length; i += 1) { - defineProperty(object, props[i], map[props[i]], predicates[props[i]]); - } -}; - -defineProperties.supportsDescriptors = !!supportsDescriptors; - -module.exports = defineProperties; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var slice = Array.prototype.slice; -var isArgs = __webpack_require__(49); - -var origKeys = Object.keys; -var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(50); - -var originalKeys = Object.keys; - -keysShim.shim = function shimObjectKeys() { - if (Object.keys) { - var keysWorksWithArguments = (function () { - // Safari 5.0 bug - var args = Object.keys(arguments); - return args && args.length === arguments.length; - }(1, 2)); - if (!keysWorksWithArguments) { - Object.keys = function keys(object) { // eslint-disable-line func-name-matching - if (isArgs(object)) { - return originalKeys(slice.call(object)); - } - return originalKeys(object); - }; - } - } else { - Object.keys = keysShim; - } - return Object.keys || keysShim; -}; - -module.exports = keysShim; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var toStr = Object.prototype.toString; - -module.exports = function isArguments(value) { - var str = toStr.call(value); - var isArgs = str === '[object Arguments]'; - if (!isArgs) { - isArgs = str !== '[object Array]' && - value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - toStr.call(value.callee) === '[object Function]'; - } - return isArgs; -}; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var keysShim; -if (!Object.keys) { - // modified from https://github.com/es-shims/es5-shim - var has = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var isArgs = __webpack_require__(49); // eslint-disable-line global-require - var isEnumerable = Object.prototype.propertyIsEnumerable; - var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); - var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); - var dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ]; - var equalsConstructorPrototype = function (o) { - var ctor = o.constructor; - return ctor && ctor.prototype === o; - }; - var excludedKeys = { - $applicationCache: true, - $console: true, - $external: true, - $frame: true, - $frameElement: true, - $frames: true, - $innerHeight: true, - $innerWidth: true, - $onmozfullscreenchange: true, - $onmozfullscreenerror: true, - $outerHeight: true, - $outerWidth: true, - $pageXOffset: true, - $pageYOffset: true, - $parent: true, - $scrollLeft: true, - $scrollTop: true, - $scrollX: true, - $scrollY: true, - $self: true, - $webkitIndexedDB: true, - $webkitStorageInfo: true, - $window: true - }; - var hasAutomationEqualityBug = (function () { - /* global window */ - if (typeof window === 'undefined') { return false; } - for (var k in window) { - try { - if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { - try { - equalsConstructorPrototype(window[k]); - } catch (e) { - return true; - } - } - } catch (e) { - return true; - } - } - return false; - }()); - var equalsConstructorPrototypeIfNotBuggy = function (o) { - /* global window */ - if (typeof window === 'undefined' || !hasAutomationEqualityBug) { - return equalsConstructorPrototype(o); - } - try { - return equalsConstructorPrototype(o); - } catch (e) { - return false; - } - }; - - keysShim = function keys(object) { - var isObject = object !== null && typeof object === 'object'; - var isFunction = toStr.call(object) === '[object Function]'; - var isArguments = isArgs(object); - var isString = isObject && toStr.call(object) === '[object String]'; - var theKeys = []; - - if (!isObject && !isFunction && !isArguments) { - throw new TypeError('Object.keys called on a non-object'); - } - - var skipProto = hasProtoEnumBug && isFunction; - if (isString && object.length > 0 && !has.call(object, 0)) { - for (var i = 0; i < object.length; ++i) { - theKeys.push(String(i)); - } - } - - if (isArguments && object.length > 0) { - for (var j = 0; j < object.length; ++j) { - theKeys.push(String(j)); - } - } else { - for (var name in object) { - if (!(skipProto && name === 'prototype') && has.call(object, name)) { - theKeys.push(String(name)); - } - } - } - - if (hasDontEnumBug) { - var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); - - for (var k = 0; k < dontEnums.length; ++k) { - if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { - theKeys.push(dontEnums[k]); - } - } - } - return theKeys; - }; -} -module.exports = keysShim; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var requirePromise = __webpack_require__(52); - -requirePromise(); - -var IsCallable = __webpack_require__(53); -var SpeciesConstructor = __webpack_require__(55); -var Type = __webpack_require__(60); - -var promiseResolve = function PromiseResolve(C, value) { - return new C(function (resolve) { - resolve(value); - }); -}; - -var OriginalPromise = Promise; - -var createThenFinally = function CreateThenFinally(C, onFinally) { - return function (value) { - var result = onFinally(); - var promise = promiseResolve(C, result); - var valueThunk = function () { - return value; - }; - return promise.then(valueThunk); - }; -}; - -var createCatchFinally = function CreateCatchFinally(C, onFinally) { - return function (reason) { - var result = onFinally(); - var promise = promiseResolve(C, result); - var thrower = function () { - throw reason; - }; - return promise.then(thrower); - }; -}; - -var promiseFinally = function finally_(onFinally) { - /* eslint no-invalid-this: 0 */ - - var promise = this; - - if (Type(promise) !== 'Object') { - throw new TypeError('receiver is not an Object'); - } - - var C = SpeciesConstructor(promise, OriginalPromise); // may throw - - var thenFinally = onFinally; - var catchFinally = onFinally; - if (IsCallable(onFinally)) { - thenFinally = createThenFinally(C, onFinally); - catchFinally = createCatchFinally(C, onFinally); - } - - return promise.then(thenFinally, catchFinally); -}; - -if (Object.getOwnPropertyDescriptor) { - var descriptor = Object.getOwnPropertyDescriptor(promiseFinally, 'name'); - if (descriptor && descriptor.configurable) { - Object.defineProperty(promiseFinally, 'name', { configurable: true, value: 'finally' }); - } -} - -module.exports = promiseFinally; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = function requirePromise() { - if (typeof Promise !== 'function') { - throw new TypeError('`Promise.prototype.finally` requires a global `Promise` be available.'); - } -}; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = __webpack_require__(54); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var fnToStr = Function.prototype.toString; - -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } catch (e) { - return false; // not a function - } -}; - -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { return false; } - fnToStr.call(value); - return true; - } catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isCallable(value) { - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - if (typeof value === 'function' && !value.prototype) { return true; } - if (hasToStringTag) { return tryFunctionObject(value); } - if (isES6ClassFn(value)) { return false; } - var strClass = toStr.call(value); - return strClass === fnClass || strClass === genClass; -}; - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var GetIntrinsic = __webpack_require__(56); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = __webpack_require__(59); -var Type = __webpack_require__(60); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* globals - Atomics, - SharedArrayBuffer, -*/ - -var undefined; - -var $TypeError = TypeError; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { throw new $TypeError(); }; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = __webpack_require__(57)(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var generator; // = function * () {}; -var generatorFunction = generator ? getProto(generator) : undefined; -var asyncFn; // async function() {}; -var asyncFunction = asyncFn ? asyncFn.constructor : undefined; -var asyncGen; // async function * () {}; -var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; -var asyncGenIterator = asyncGen ? asyncGen() : undefined; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%ArrayPrototype%': Array.prototype, - '%ArrayProto_entries%': Array.prototype.entries, - '%ArrayProto_forEach%': Array.prototype.forEach, - '%ArrayProto_keys%': Array.prototype.keys, - '%ArrayProto_values%': Array.prototype.values, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': asyncFunction, - '%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, - '%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, - '%AsyncGeneratorFunction%': asyncGenFunction, - '%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, - '%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%Boolean%': Boolean, - '%BooleanPrototype%': Boolean.prototype, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, - '%Date%': Date, - '%DatePrototype%': Date.prototype, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%ErrorPrototype%': Error.prototype, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%EvalErrorPrototype%': EvalError.prototype, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, - '%Function%': Function, - '%FunctionPrototype%': Function.prototype, - '%Generator%': generator ? getProto(generator()) : undefined, - '%GeneratorFunction%': generatorFunction, - '%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, - '%Math%': Math, - '%Number%': Number, - '%NumberPrototype%': Number.prototype, - '%Object%': Object, - '%ObjectPrototype%': Object.prototype, - '%ObjProto_toString%': Object.prototype.toString, - '%ObjProto_valueOf%': Object.prototype.valueOf, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, - '%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, - '%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, - '%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, - '%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%RangeErrorPrototype%': RangeError.prototype, - '%ReferenceError%': ReferenceError, - '%ReferenceErrorPrototype%': ReferenceError.prototype, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%RegExpPrototype%': RegExp.prototype, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%StringPrototype%': String.prototype, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, - '%SyntaxError%': SyntaxError, - '%SyntaxErrorPrototype%': SyntaxError.prototype, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, - '%TypeError%': $TypeError, - '%TypeErrorPrototype%': $TypeError.prototype, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, - '%URIError%': URIError, - '%URIErrorPrototype%': URIError.prototype, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - '%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype -}; - -var bind = __webpack_require__(45); -var $replace = bind.call(Function.call, String.prototype.replace); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - if (!(name in INTRINSICS)) { - throw new SyntaxError('intrinsic ' + name + ' does not exist!'); - } - - // istanbul ignore if // hopefully this is impossible to test :-) - if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return INTRINSICS[name]; -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - - var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing); - for (var i = 1; i < parts.length; i += 1) { - if (value != null) { - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, parts[i]); - if (!allowMissing && !(parts[i] in value)) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - value = desc ? (desc.get || desc.value) : value[parts[i]]; - } else { - value = value[parts[i]]; - } - } - } - return value; -}; - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var origSymbol = global.Symbol; -var hasSymbolSham = __webpack_require__(58); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var ES5Type = __webpack_require__(61); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// https://www.ecma-international.org/ecma-262/5.1/#sec-8 - -module.exports = function Type(x) { - if (x === null) { - return 'Null'; - } - if (typeof x === 'undefined') { - return 'Undefined'; - } - if (typeof x === 'function' || typeof x === 'object') { - return 'Object'; - } - if (typeof x === 'number') { - return 'Number'; - } - if (typeof x === 'boolean') { - return 'Boolean'; - } - if (typeof x === 'string') { - return 'String'; - } -}; - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var requirePromise = __webpack_require__(52); - -var implementation = __webpack_require__(51); - -module.exports = function getPolyfill() { - requirePromise(); - return typeof Promise.prototype['finally'] === 'function' ? Promise.prototype['finally'] : implementation; -}; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var requirePromise = __webpack_require__(52); - -var getPolyfill = __webpack_require__(62); -var define = __webpack_require__(47); - -module.exports = function shimPromiseFinally() { - requirePromise(); - - var polyfill = getPolyfill(); - define(Promise.prototype, { 'finally': polyfill }, { - 'finally': function testFinally() { - return Promise.prototype['finally'] !== polyfill; - } - }); - return polyfill; -}; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const log4js_1 = tslib_1.__importDefault(__webpack_require__(67)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -function getLogFile() { - let file = process.env.NVIM_COC_LOG_FILE; - if (file) - return file; - let dir = process.env.XDG_RUNTIME_DIR; - if (dir) { - try { - fs_1.default.accessSync(dir, fs_1.default.constants.R_OK | fs_1.default.constants.W_OK); - return path_1.default.join(dir, `coc-nvim-${process.pid}.log`); - } - catch (err) { - // noop - } - } - dir = path_1.default.join(process.env.TMPDIR, `coc.nvim-${process.pid}`); - if (os_1.default.platform() == 'win32') { - dir = path_1.default.win32.normalize(dir); - } - if (!fs_1.default.existsSync(dir)) - fs_1.default.mkdirSync(dir, { recursive: true }); - return path_1.default.join(dir, `coc-nvim.log`); -} -const MAX_LOG_SIZE = 1024 * 1024; -const MAX_LOG_BACKUPS = 10; -let logfile = getLogFile(); -const level = process.env.NVIM_COC_LOG_LEVEL || 'info'; -if (fs_1.default.existsSync(logfile)) { - // cleanup if exists - try { - fs_1.default.writeFileSync(logfile, '', { encoding: 'utf8', mode: 0o666 }); - } - catch (e) { - // noop - } -} -log4js_1.default.configure({ - disableClustering: true, - appenders: { - out: { - type: 'file', - mode: 0o666, - filename: logfile, - maxLogSize: MAX_LOG_SIZE, - backups: MAX_LOG_BACKUPS, - layout: { - type: 'pattern', - // Format log in following pattern: - // yyyy-MM-dd HH:mm:ss.mil $Level (pid:$pid) $categroy - $message. - pattern: `%d{ISO8601} %p (pid:${process.pid}) [%c] - %m`, - }, - } - }, - categories: { - default: { appenders: ['out'], level } - } -}); -module.exports = (name = 'coc-nvim') => { - let logger = log4js_1.default.getLogger(name); - logger.getLogFile = () => logfile; - return logger; -}; -//# sourceMappingURL=logger.js.map - -/***/ }), -/* 65 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -var __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); - -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} - -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; -} - - -/***/ }), -/* 66 */ -/***/ (function(module, exports) { - -module.exports = require("fs"); - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @fileoverview log4js is a library to log in JavaScript in similar manner - * than in log4j for Java (but not really). - * - *

Example:

- *
- *  const logging = require('log4js');
- *  const log = logging.getLogger('some-category');
- *
- *  //call the log
- *  log.trace('trace me' );
- * 
- * - * NOTE: the authors below are the original browser-based log4js authors - * don't try to contact them about bugs in this version :) - * @author Stephan Strittmatter - http://jroller.com/page/stritti - * @author Seth Chisamore - http://www.chisamore.com - * @since 2005-05-20 - * Website: http://log4js.berlios.de - */ -const debug = __webpack_require__(68)("log4js:main"); -const fs = __webpack_require__(66); -const deepClone = __webpack_require__(78)({ proto: true }); -const configuration = __webpack_require__(79); -const layouts = __webpack_require__(80); -const levels = __webpack_require__(83); -const appenders = __webpack_require__(84); -const categories = __webpack_require__(151); -const Logger = __webpack_require__(152); -const clustering = __webpack_require__(85); -const connectLogger = __webpack_require__(153); - -let enabled = false; - -function sendLogEventToAppender(logEvent) { - if (!enabled) return; - debug("Received log event ", logEvent); - const categoryAppenders = categories.appendersForCategory( - logEvent.categoryName - ); - categoryAppenders.forEach(appender => { - appender(logEvent); - }); -} - -function loadConfigurationFile(filename) { - debug(`Loading configuration from ${filename}`); - try { - return JSON.parse(fs.readFileSync(filename, "utf8")); - } catch (e) { - throw new Error( - `Problem reading config from file "${filename}". Error was ${e.message}`, - e - ); - } -} - -function configure(configurationFileOrObject) { - let configObject = configurationFileOrObject; - - if (typeof configObject === "string") { - configObject = loadConfigurationFile(configurationFileOrObject); - } - debug(`Configuration is ${configObject}`); - - configuration.configure(deepClone(configObject)); - - clustering.onMessage(sendLogEventToAppender); - - enabled = true; - - // eslint-disable-next-line no-use-before-define - return log4js; -} - -/** - * Shutdown all log appenders. This will first disable all writing to appenders - * and then call the shutdown function each appender. - * - * @params {Function} cb - The callback to be invoked once all appenders have - * shutdown. If an error occurs, the callback will be given the error object - * as the first argument. - */ -function shutdown(cb) { - debug("Shutdown called. Disabling all log writing."); - // First, disable all writing to appenders. This prevents appenders from - // not being able to be drained because of run-away log writes. - enabled = false; - - // Call each of the shutdown functions in parallel - const appendersToCheck = Array.from(appenders.values()); - const shutdownFunctions = appendersToCheck.reduceRight( - (accum, next) => (next.shutdown ? accum + 1 : accum), - 0 - ); - let completed = 0; - let error; - - debug(`Found ${shutdownFunctions} appenders with shutdown functions.`); - function complete(err) { - error = error || err; - completed += 1; - debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`); - if (completed >= shutdownFunctions) { - debug("All shutdown functions completed."); - if (cb) { - cb(error); - } - } - } - - if (shutdownFunctions === 0) { - debug("No appenders with shutdown functions found."); - return cb !== undefined && cb(); - } - - appendersToCheck.filter(a => a.shutdown).forEach(a => a.shutdown(complete)); - - return null; -} - -/** - * Get a logger instance. - * @static - * @param loggerCategoryName - * @return {Logger} instance of logger for the category - */ -function getLogger(category) { - if (!enabled) { - configure( - process.env.LOG4JS_CONFIG || { - appenders: { out: { type: "stdout" } }, - categories: { default: { appenders: ["out"], level: "OFF" } } - } - ); - } - return new Logger(category || "default"); -} - -/** - * @name log4js - * @namespace Log4js - * @property getLogger - * @property configure - * @property shutdown - */ -const log4js = { - getLogger, - configure, - shutdown, - connectLogger, - levels, - addLayout: layouts.addLayout -}; - -module.exports = log4js; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(69); -} else { - module.exports = __webpack_require__(72); -} - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ -function log(...args) { - // This hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return typeof console === 'object' && - console.log && - console.log(...args); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(70)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(71); - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * Active `debug` instances. - */ - createDebug.instances = []; - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return match; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = createDebug.enabled(namespace); - debug.useColors = createDebug.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - debug.extend = extend; - // Debug.formatArgs = formatArgs; - // debug.rawLog = rawLog; - - // env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - createDebug.instances.push(debug); - - return debug; - } - - function destroy() { - const index = createDebug.instances.indexOf(this); - if (index !== -1) { - createDebug.instances.splice(index, 1); - return true; - } - return false; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - - for (i = 0; i < createDebug.instances.length; i++) { - const instance = createDebug.instances[i]; - instance.enabled = createDebug.enabled(instance.namespace); - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports) { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Module dependencies. - */ - -const tty = __webpack_require__(73); -const util = __webpack_require__(74); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(75); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __webpack_require__(70)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .replace(/\s*\n\s*/g, ' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports) { - -module.exports = require("tty"); - -/***/ }), -/* 74 */ -/***/ (function(module, exports) { - -module.exports = require("util"); - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const os = __webpack_require__(76); -const tty = __webpack_require__(73); -const hasFlag = __webpack_require__(77); - -const {env} = process; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} - -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } - - const min = forceColor || 0; - - if (env.TERM === 'dumb') { - return min; - } - - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if ('GITHUB_ACTIONS' in env) { - return 1; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports) { - -module.exports = require("os"); - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = rfdc - -function rfdc (opts) { - opts = opts || {} - - if (opts.circles) return rfdcCircles(opts) - return opts.proto ? cloneProto : clone - - function cloneArray (a, fn) { - var keys = Object.keys(a) - var a2 = new Array(keys.length) - for (var i = 0; i < keys.length; i++) { - var k = keys[i] - var cur = a[k] - if (typeof cur !== 'object' || cur === null) { - a2[k] = cur - } else if (cur instanceof Date) { - a2[k] = new Date(cur) - } else { - a2[k] = fn(cur) - } - } - return a2 - } - - function clone (o) { - if (typeof o !== 'object' || o === null) return o - if (o instanceof Date) return new Date(o) - if (Array.isArray(o)) return cloneArray(o, clone) - var o2 = {} - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) continue - var cur = o[k] - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur - } else if (cur instanceof Date) { - o2[k] = new Date(cur) - } else { - o2[k] = clone(cur) - } - } - return o2 - } - - function cloneProto (o) { - if (typeof o !== 'object' || o === null) return o - if (o instanceof Date) return new Date(o) - if (Array.isArray(o)) return cloneArray(o, cloneProto) - var o2 = {} - for (var k in o) { - var cur = o[k] - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur - } else if (cur instanceof Date) { - o2[k] = new Date(cur) - } else { - o2[k] = cloneProto(cur) - } - } - return o2 - } -} - -function rfdcCircles (opts) { - var refs = [] - var refsNew = [] - - return opts.proto ? cloneProto : clone - - function cloneArray (a, fn) { - var keys = Object.keys(a) - var a2 = new Array(keys.length) - for (var i = 0; i < keys.length; i++) { - var k = keys[i] - var cur = a[k] - if (typeof cur !== 'object' || cur === null) { - a2[k] = cur - } else if (cur instanceof Date) { - a2[k] = new Date(cur) - } else { - var index = refs.indexOf(cur) - if (index !== -1) { - a2[k] = refsNew[index] - } else { - a2[k] = fn(cur) - } - } - } - return a2 - } - - function clone (o) { - if (typeof o !== 'object' || o === null) return o - if (o instanceof Date) return new Date(o) - if (Array.isArray(o)) return cloneArray(o, clone) - var o2 = {} - refs.push(o) - refsNew.push(o2) - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) continue - var cur = o[k] - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur - } else if (cur instanceof Date) { - o2[k] = new Date(cur) - } else { - var i = refs.indexOf(cur) - if (i !== -1) { - o2[k] = refsNew[i] - } else { - o2[k] = clone(cur) - } - } - } - refs.pop() - refsNew.pop() - return o2 - } - - function cloneProto (o) { - if (typeof o !== 'object' || o === null) return o - if (o instanceof Date) return new Date(o) - if (Array.isArray(o)) return cloneArray(o, cloneProto) - var o2 = {} - refs.push(o) - refsNew.push(o2) - for (var k in o) { - var cur = o[k] - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur - } else if (cur instanceof Date) { - o2[k] = new Date(cur) - } else { - var i = refs.indexOf(cur) - if (i !== -1) { - o2[k] = refsNew[i] - } else { - o2[k] = cloneProto(cur) - } - } - } - refs.pop() - refsNew.pop() - return o2 - } -} - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - - -const util = __webpack_require__(74); -const debug = __webpack_require__(68)('log4js:configuration'); - -const preProcessingListeners = []; -const listeners = []; - -const not = thing => !thing; - -const anObject = thing => thing && typeof thing === 'object' && !Array.isArray(thing); - -const validIdentifier = thing => /^[A-Za-z][A-Za-z0-9_]*$/g.test(thing); - -const anInteger = thing => thing && typeof thing === 'number' && Number.isInteger(thing); - -const addListener = (fn) => { - listeners.push(fn); - debug(`Added listener, now ${listeners.length} listeners`); -}; - -const addPreProcessingListener = (fn) => { - preProcessingListeners.push(fn); - debug(`Added pre-processing listener, now ${preProcessingListeners.length} listeners`); -}; - -const throwExceptionIf = (config, checks, message) => { - const tests = Array.isArray(checks) ? checks : [checks]; - tests.forEach((test) => { - if (test) { - throw new Error(`Problem with log4js configuration: (${util.inspect(config, { depth: 5 })})` - + ` - ${message}`); - } - }); -}; - -const configure = (candidate) => { - debug('New configuration to be validated: ', candidate); - throwExceptionIf(candidate, not(anObject(candidate)), 'must be an object.'); - - debug(`Calling pre-processing listeners (${preProcessingListeners.length})`); - preProcessingListeners.forEach(listener => listener(candidate)); - debug('Configuration pre-processing finished.'); - - debug(`Calling configuration listeners (${listeners.length})`); - listeners.forEach(listener => listener(candidate)); - debug('Configuration finished.'); -}; - -module.exports = { - configure, - addListener, - addPreProcessingListener, - throwExceptionIf, - anObject, - anInteger, - validIdentifier, - not -}; - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -const dateFormat = __webpack_require__(81); -const os = __webpack_require__(76); -const util = __webpack_require__(74); -const path = __webpack_require__(82); - -const styles = { - // styles - bold: [1, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - // grayscale - white: [37, 39], - grey: [90, 39], - black: [90, 39], - // colors - blue: [34, 39], - cyan: [36, 39], - green: [32, 39], - magenta: [35, 39], - red: [91, 39], - yellow: [33, 39] -}; - -function colorizeStart(style) { - return style ? `\x1B[${styles[style][0]}m` : ''; -} - -function colorizeEnd(style) { - return style ? `\x1B[${styles[style][1]}m` : ''; -} - -/** - * Taken from masylum's fork (https://github.com/masylum/log4js-node) - */ -function colorize(str, style) { - return colorizeStart(style) + str + colorizeEnd(style); -} - -function timestampLevelAndCategory(loggingEvent, colour) { - return colorize( - util.format( - '[%s] [%s] %s - ', - dateFormat.asString(loggingEvent.startTime), - loggingEvent.level.toString(), - loggingEvent.categoryName - ), - colour - ); -} - -/** - * BasicLayout is a simple layout for storing the logs. The logs are stored - * in following format: - *
- * [startTime] [logLevel] categoryName - message\n
- * 
- * - * @author Stephan Strittmatter - */ -function basicLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent) + util.format(...loggingEvent.data); -} - -/** - * colouredLayout - taken from masylum's fork. - * same as basicLayout, but with colours. - */ -function colouredLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent, loggingEvent.level.colour) + util.format(...loggingEvent.data); -} - -function messagePassThroughLayout(loggingEvent) { - return util.format(...loggingEvent.data); -} - -function dummyLayout(loggingEvent) { - return loggingEvent.data[0]; -} - -/** - * PatternLayout - * Format for specifiers is %[padding].[truncation][field]{[format]} - * e.g. %5.10p - left pad the log level by 5 characters, up to a max of 10 - * both padding and truncation can be negative. - * Negative truncation = trunc from end of string - * Positive truncation = trunc from start of string - * Negative padding = pad right - * Positive padding = pad left - * - * Fields can be any of: - * - %r time in toLocaleTimeString format - * - %p log level - * - %c log category - * - %h hostname - * - %m log data - * - %d date in constious formats - * - %% % - * - %n newline - * - %z pid - * - %f filename - * - %l line number - * - %o column postion - * - %s call stack - * - %x{} add dynamic tokens to your log. Tokens are specified in the tokens parameter - * - %X{} add dynamic tokens to your log. Tokens are specified in logger context - * You can use %[ and %] to define a colored block. - * - * Tokens are specified as simple key:value objects. - * The key represents the token name whereas the value can be a string or function - * which is called to extract the value to put in the log message. If token is not - * found, it doesn't replace the field. - * - * A sample token would be: { 'pid' : function() { return process.pid; } } - * - * Takes a pattern string, array of tokens and returns a layout function. - * @return {Function} - * @param pattern - * @param tokens - * @param timezoneOffset - * - * @authors ['Stephan Strittmatter', 'Jan Schmidle'] - */ -function patternLayout(pattern, tokens) { - const TTCC_CONVERSION_PATTERN = '%r %p %c - %m%n'; - const regex = /%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/; - - pattern = pattern || TTCC_CONVERSION_PATTERN; - - function categoryName(loggingEvent, specifier) { - let loggerName = loggingEvent.categoryName; - if (specifier) { - const precision = parseInt(specifier, 10); - const loggerNameBits = loggerName.split('.'); - if (precision < loggerNameBits.length) { - loggerName = loggerNameBits.slice(loggerNameBits.length - precision).join('.'); - } - } - return loggerName; - } - - function formatAsDate(loggingEvent, specifier) { - let format = dateFormat.ISO8601_FORMAT; - if (specifier) { - format = specifier; - // Pick up special cases - if (format === 'ISO8601') { - format = dateFormat.ISO8601_FORMAT; - } else if (format === 'ISO8601_WITH_TZ_OFFSET') { - format = dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT; - } else if (format === 'ABSOLUTE') { - format = dateFormat.ABSOLUTETIME_FORMAT; - } else if (format === 'DATE') { - format = dateFormat.DATETIME_FORMAT; - } - } - // Format the date - return dateFormat.asString(format, loggingEvent.startTime); - } - - function hostname() { - return os.hostname().toString(); - } - - function formatMessage(loggingEvent) { - return util.format(...loggingEvent.data); - } - - function endOfLine() { - return os.EOL; - } - - function logLevel(loggingEvent) { - return loggingEvent.level.toString(); - } - - function startTime(loggingEvent) { - return dateFormat.asString('hh:mm:ss', loggingEvent.startTime); - } - - function startColour(loggingEvent) { - return colorizeStart(loggingEvent.level.colour); - } - - function endColour(loggingEvent) { - return colorizeEnd(loggingEvent.level.colour); - } - - function percent() { - return '%'; - } - - function pid(loggingEvent) { - return loggingEvent && loggingEvent.pid ? loggingEvent.pid.toString() : process.pid.toString(); - } - - function clusterInfo() { - // this used to try to return the master and worker pids, - // but it would never have worked because master pid is not available to workers - // leaving this here to maintain compatibility for patterns - return pid(); - } - - function userDefined(loggingEvent, specifier) { - if (typeof tokens[specifier] !== 'undefined') { - return typeof tokens[specifier] === 'function' ? tokens[specifier](loggingEvent) : tokens[specifier]; - } - - return null; - } - - function contextDefined(loggingEvent, specifier) { - const resolver = loggingEvent.context[specifier]; - - if (typeof resolver !== 'undefined') { - return typeof resolver === 'function' ? resolver(loggingEvent) : resolver; - } - - return null; - } - - function fileName(loggingEvent, specifier) { - let filename = loggingEvent.fileName || ''; - if (specifier) { - const fileDepth = parseInt(specifier, 10); - const fileList = filename.split(path.sep); - if (fileList.length > fileDepth) { - filename = fileList.slice(-fileDepth).join(path.sep); - } - } - - return filename; - } - - function lineNumber(loggingEvent) { - return loggingEvent.lineNumber ? `${loggingEvent.lineNumber}` : ''; - } - - function columnNumber(loggingEvent) { - return loggingEvent.columnNumber ? `${loggingEvent.columnNumber}` : ''; - } - - function callStack(loggingEvent) { - return loggingEvent.callStack || ''; - } - - /* eslint quote-props:0 */ - const replacers = { - c: categoryName, - d: formatAsDate, - h: hostname, - m: formatMessage, - n: endOfLine, - p: logLevel, - r: startTime, - '[': startColour, - ']': endColour, - y: clusterInfo, - z: pid, - '%': percent, - x: userDefined, - X: contextDefined, - f: fileName, - l: lineNumber, - o: columnNumber, - s: callStack - }; - - function replaceToken(conversionCharacter, loggingEvent, specifier) { - return replacers[conversionCharacter](loggingEvent, specifier); - } - - function truncate(truncation, toTruncate) { - let len; - if (truncation) { - len = parseInt(truncation.substr(1), 10); - // negative truncate length means truncate from end of string - return len > 0 ? toTruncate.slice(0, len) : toTruncate.slice(len); - } - - return toTruncate; - } - - function pad(padding, toPad) { - let len; - if (padding) { - if (padding.charAt(0) === '-') { - len = parseInt(padding.substr(1), 10); - // Right pad with spaces - while (toPad.length < len) { - toPad += ' '; - } - } else { - len = parseInt(padding, 10); - // Left pad with spaces - while (toPad.length < len) { - toPad = ` ${toPad}`; - } - } - } - return toPad; - } - - function truncateAndPad(toTruncAndPad, truncation, padding) { - let replacement = toTruncAndPad; - replacement = truncate(truncation, replacement); - replacement = pad(padding, replacement); - return replacement; - } - - return function (loggingEvent) { - let formattedString = ''; - let result; - let searchString = pattern; - - /* eslint no-cond-assign:0 */ - while ((result = regex.exec(searchString)) !== null) { - // const matchedString = result[0]; - const padding = result[1]; - const truncation = result[2]; - const conversionCharacter = result[3]; - const specifier = result[5]; - const text = result[6]; - - // Check if the pattern matched was just normal text - if (text) { - formattedString += text.toString(); - } else { - // Create a raw replacement string based on the conversion - // character and specifier - const replacement = replaceToken(conversionCharacter, loggingEvent, specifier); - formattedString += truncateAndPad(replacement, truncation, padding); - } - searchString = searchString.substr(result.index + result[0].length); - } - return formattedString; - }; -} - -const layoutMakers = { - messagePassThrough () { - return messagePassThroughLayout; - }, - basic () { - return basicLayout; - }, - colored () { - return colouredLayout; - }, - coloured () { - return colouredLayout; - }, - pattern (config) { - return patternLayout(config && config.pattern, config && config.tokens); - }, - dummy () { - return dummyLayout; - } -}; - -module.exports = { - basicLayout, - messagePassThroughLayout, - patternLayout, - colouredLayout, - coloredLayout: colouredLayout, - dummyLayout, - addLayout (name, serializerGenerator) { - layoutMakers[name] = serializerGenerator; - }, - layout (name, config) { - return layoutMakers[name] && layoutMakers[name](config); - } -}; - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -function padWithZeros(vNumber, width) { - var numAsString = vNumber.toString(); - while (numAsString.length < width) { - numAsString = "0" + numAsString; - } - return numAsString; -} - -function addZero(vNumber) { - return padWithZeros(vNumber, 2); -} - -/** - * Formats the TimeOffset - * Thanks to http://www.svendtofte.com/code/date_format/ - * @private - */ -function offset(timezoneOffset) { - var os = Math.abs(timezoneOffset); - var h = String(Math.floor(os / 60)); - var m = String(os % 60); - if (h.length === 1) { - h = "0" + h; - } - if (m.length === 1) { - m = "0" + m; - } - return timezoneOffset < 0 ? "+" + h + m : "-" + h + m; -} - -function asString(format, date) { - if (typeof format !== "string") { - date = format; - format = module.exports.ISO8601_FORMAT; - } - if (!date) { - date = module.exports.now(); - } - - // Issue # 14 - Per ISO8601 standard, the time string should be local time - // with timezone info. - // See https://en.wikipedia.org/wiki/ISO_8601 section "Time offsets from UTC" - - var vDay = addZero(date.getDate()); - var vMonth = addZero(date.getMonth() + 1); - var vYearLong = addZero(date.getFullYear()); - var vYearShort = addZero(vYearLong.substring(2, 4)); - var vYear = format.indexOf("yyyy") > -1 ? vYearLong : vYearShort; - var vHour = addZero(date.getHours()); - var vMinute = addZero(date.getMinutes()); - var vSecond = addZero(date.getSeconds()); - var vMillisecond = padWithZeros(date.getMilliseconds(), 3); - var vTimeZone = offset(date.getTimezoneOffset()); - var formatted = format - .replace(/dd/g, vDay) - .replace(/MM/g, vMonth) - .replace(/y{1,4}/g, vYear) - .replace(/hh/g, vHour) - .replace(/mm/g, vMinute) - .replace(/ss/g, vSecond) - .replace(/SSS/g, vMillisecond) - .replace(/O/g, vTimeZone); - return formatted; -} - -function setDatePart(date, part, value, local) { - date['set' + (local ? '' : 'UTC') + part](value); -} - -function extractDateParts(pattern, str, missingValuesDate) { - // Javascript Date object doesn't support custom timezone. Sets all felds as - // GMT based to begin with. If the timezone offset is provided, then adjust - // it using provided timezone, otherwise, adjust it with the system timezone. - var local = pattern.indexOf('O') < 0; - var matchers = [ - { - pattern: /y{1,4}/, - regexp: "\\d{1,4}", - fn: function(date, value) { - setDatePart(date, 'FullYear', value, local); - } - }, - { - pattern: /MM/, - regexp: "\\d{1,2}", - fn: function(date, value) { - setDatePart(date, 'Month', (value - 1), local); - } - }, - { - pattern: /dd/, - regexp: "\\d{1,2}", - fn: function(date, value) { - setDatePart(date, 'Date', value, local); - } - }, - { - pattern: /hh/, - regexp: "\\d{1,2}", - fn: function(date, value) { - setDatePart(date, 'Hours', value, local); - } - }, - { - pattern: /mm/, - regexp: "\\d\\d", - fn: function(date, value) { - setDatePart(date, 'Minutes', value, local); - } - }, - { - pattern: /ss/, - regexp: "\\d\\d", - fn: function(date, value) { - setDatePart(date, 'Seconds', value, local); - } - }, - { - pattern: /SSS/, - regexp: "\\d\\d\\d", - fn: function(date, value) { - setDatePart(date, 'Milliseconds', value, local); - } - }, - { - pattern: /O/, - regexp: "[+-]\\d{3,4}|Z", - fn: function(date, value) { - if (value === "Z") { - value = 0; - } - var offset = Math.abs(value); - var timezoneOffset = (value > 0 ? -1 : 1 ) * ((offset % 100) + Math.floor(offset / 100) * 60); - // Per ISO8601 standard: UTC = local time - offset - // - // For example, 2000-01-01T01:00:00-0700 - // local time: 2000-01-01T01:00:00 - // ==> UTC : 2000-01-01T08:00:00 ( 01 - (-7) = 8 ) - // - // To make it even more confusing, the date.getTimezoneOffset() is - // opposite sign of offset string in the ISO8601 standard. So if offset - // is '-0700' the getTimezoneOffset() would be (+)420. The line above - // calculates timezoneOffset to matche Javascript's behavior. - // - // The date/time of the input is actually the local time, so the date - // object that was constructed is actually local time even thought the - // UTC setters are used. This means the date object's internal UTC - // representation was wrong. It needs to be fixed by substracting the - // offset (or adding the offset minutes as they are opposite sign). - // - // Note: the time zone has to be processed after all other fileds are - // set. The result would be incorrect if the offset was calculated - // first then overriden by the other filed setters. - date.setUTCMinutes(date.getUTCMinutes() + timezoneOffset); - } - } - ]; - - var parsedPattern = matchers.reduce( - function(p, m) { - if (m.pattern.test(p.regexp)) { - m.index = p.regexp.match(m.pattern).index; - p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")"); - } else { - m.index = -1; - } - return p; - }, - { regexp: pattern, index: [] } - ); - - var dateFns = matchers.filter(function(m) { - return m.index > -1; - }); - dateFns.sort(function(a, b) { - return a.index - b.index; - }); - - var matcher = new RegExp(parsedPattern.regexp); - var matches = matcher.exec(str); - if (matches) { - var date = missingValuesDate || module.exports.now(); - dateFns.forEach(function(f, i) { - f.fn(date, matches[i + 1]); - }); - - return date; - } - - throw new Error( - "String '" + str + "' could not be parsed as '" + pattern + "'" - ); -} - -function parse(pattern, str, missingValuesDate) { - if (!pattern) { - throw new Error("pattern must be supplied"); - } - - return extractDateParts(pattern, str, missingValuesDate); -} - -/** - * Used for testing - replace this function with a fixed date. - */ -function now() { - return new Date(); -} - -module.exports = asString; -module.exports.asString = asString; -module.exports.parse = parse; -module.exports.now = now; -module.exports.ISO8601_FORMAT = "yyyy-MM-ddThh:mm:ss.SSS"; -module.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ss.SSSO"; -module.exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS"; -module.exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS"; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports) { - -module.exports = require("path"); - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - - - -const configuration = __webpack_require__(79); - -const validColours = [ - 'white', 'grey', 'black', - 'blue', 'cyan', 'green', - 'magenta', 'red', 'yellow' -]; - -class Level { - constructor(level, levelStr, colour) { - this.level = level; - this.levelStr = levelStr; - this.colour = colour; - } - - toString() { - return this.levelStr; - } - - /** - * converts given String to corresponding Level - * @param {(Level|string)} sArg -- String value of Level OR Log4js.Level - * @param {Level} [defaultLevel] -- default Level, if no String representation - * @return {Level} - */ - static getLevel(sArg, defaultLevel) { - if (!sArg) { - return defaultLevel; - } - - if (sArg instanceof Level) { - return sArg; - } - - // a json-serialised level won't be an instance of Level (see issue #768) - if (sArg instanceof Object && sArg.levelStr) { - sArg = sArg.levelStr; - } - - return Level[sArg.toString().toUpperCase()] || defaultLevel; - } - - static addLevels(customLevels) { - if (customLevels) { - const levels = Object.keys(customLevels); - levels.forEach((l) => { - const levelStr = l.toUpperCase(); - Level[levelStr] = new Level( - customLevels[l].value, - levelStr, - customLevels[l].colour - ); - const existingLevelIndex = Level.levels.findIndex(lvl => lvl.levelStr === levelStr); - if (existingLevelIndex > -1) { - Level.levels[existingLevelIndex] = Level[levelStr]; - } else { - Level.levels.push(Level[levelStr]); - } - }); - Level.levels.sort((a, b) => a.level - b.level); - } - } - - - isLessThanOrEqualTo(otherLevel) { - if (typeof otherLevel === 'string') { - otherLevel = Level.getLevel(otherLevel); - } - return this.level <= otherLevel.level; - } - - isGreaterThanOrEqualTo(otherLevel) { - if (typeof otherLevel === 'string') { - otherLevel = Level.getLevel(otherLevel); - } - return this.level >= otherLevel.level; - } - - isEqualTo(otherLevel) { - if (typeof otherLevel === 'string') { - otherLevel = Level.getLevel(otherLevel); - } - return this.level === otherLevel.level; - } -} - -Level.levels = []; -Level.addLevels({ - ALL: { value: Number.MIN_VALUE, colour: 'grey' }, - TRACE: { value: 5000, colour: 'blue' }, - DEBUG: { value: 10000, colour: 'cyan' }, - INFO: { value: 20000, colour: 'green' }, - WARN: { value: 30000, colour: 'yellow' }, - ERROR: { value: 40000, colour: 'red' }, - FATAL: { value: 50000, colour: 'magenta' }, - MARK: { value: 9007199254740992, colour: 'grey' }, // 2^53 - OFF: { value: Number.MAX_VALUE, colour: 'grey' } -}); - -configuration.addListener((config) => { - const levelConfig = config.levels; - if (levelConfig) { - configuration.throwExceptionIf( - config, - configuration.not(configuration.anObject(levelConfig)), - 'levels must be an object' - ); - const newLevels = Object.keys(levelConfig); - newLevels.forEach((l) => { - configuration.throwExceptionIf( - config, - configuration.not(configuration.validIdentifier(l)), - `level name "${l}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)` - ); - configuration.throwExceptionIf( - config, - configuration.not(configuration.anObject(levelConfig[l])), - `level "${l}" must be an object` - ); - configuration.throwExceptionIf( - config, - configuration.not(levelConfig[l].value), - `level "${l}" must have a 'value' property` - ); - configuration.throwExceptionIf( - config, - configuration.not(configuration.anInteger(levelConfig[l].value)), - `level "${l}".value must have an integer value` - ); - configuration.throwExceptionIf( - config, - configuration.not(levelConfig[l].colour), - `level "${l}" must have a 'colour' property` - ); - configuration.throwExceptionIf( - config, - configuration.not(validColours.indexOf(levelConfig[l].colour) > -1), - `level "${l}".colour must be one of ${validColours.join(', ')}` - ); - }); - } -}); - -configuration.addListener((config) => { - Level.addLevels(config.levels); -}); - -module.exports = Level; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -const path = __webpack_require__(82); -const debug = __webpack_require__(68)('log4js:appenders'); -const configuration = __webpack_require__(79); -const clustering = __webpack_require__(85); -const levels = __webpack_require__(83); -const layouts = __webpack_require__(80); -const adapters = __webpack_require__(89); - -// pre-load the core appenders so that webpack can find them -const coreAppenders = new Map(); -coreAppenders.set('console', __webpack_require__(90)); -coreAppenders.set('stdout', __webpack_require__(91)); -coreAppenders.set('stderr', __webpack_require__(92)); -coreAppenders.set('logLevelFilter', __webpack_require__(93)); -coreAppenders.set('categoryFilter', __webpack_require__(94)); -coreAppenders.set('noLogFilter', __webpack_require__(95)); -coreAppenders.set('file', __webpack_require__(96)); -coreAppenders.set('dateFile', __webpack_require__(148)); -coreAppenders.set('fileSync', __webpack_require__(149)); - -const appenders = new Map(); - -const tryLoading = (modulePath, config) => { - debug('Loading module from ', modulePath); - try { - return __webpack_require__(150)(modulePath); //eslint-disable-line - } catch (e) { - // if the module was found, and we still got an error, then raise it - configuration.throwExceptionIf( - config, - e.code !== 'MODULE_NOT_FOUND', - `appender "${modulePath}" could not be loaded (error was: ${e})` - ); - return undefined; - } -}; - -const loadAppenderModule = (type, config) => coreAppenders.get(type) - || tryLoading(`./${type}`, config) - || tryLoading(type, config) - || (__webpack_require__.c[__webpack_require__.s] && tryLoading(path.join(path.dirname(__webpack_require__.c[__webpack_require__.s].filename), type), config)) - || tryLoading(path.join(process.cwd(), type), config); - -const appendersLoading = new Set(); - -const getAppender = (name, config) => { - if (appenders.has(name)) return appenders.get(name); - if (!config.appenders[name]) return false; - if (appendersLoading.has(name)) throw new Error(`Dependency loop detected for appender ${name}.`); - appendersLoading.add(name); - - debug(`Creating appender ${name}`); - // eslint-disable-next-line no-use-before-define - const appender = createAppender(name, config); - appendersLoading.delete(name); - appenders.set(name, appender); - return appender; -}; - -const createAppender = (name, config) => { - const appenderConfig = config.appenders[name]; - const appenderModule = appenderConfig.type.configure - ? appenderConfig.type : loadAppenderModule(appenderConfig.type, config); - configuration.throwExceptionIf( - config, - configuration.not(appenderModule), - `appender "${name}" is not valid (type "${appenderConfig.type}" could not be found)` - ); - if (appenderModule.appender) { - debug(`DEPRECATION: Appender ${appenderConfig.type} exports an appender function.`); - } - if (appenderModule.shutdown) { - debug(`DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.`); - } - - debug(`${name}: clustering.isMaster ? ${clustering.isMaster()}`); - debug(`${name}: appenderModule is ${__webpack_require__(74).inspect(appenderModule)}`); // eslint-disable-line - return clustering.onlyOnMaster(() => { - debug(`calling appenderModule.configure for ${name} / ${appenderConfig.type}`); - return appenderModule.configure( - adapters.modifyConfig(appenderConfig), - layouts, - appender => getAppender(appender, config), - levels - ); - }, () => { }); -}; - -const setup = (config) => { - appenders.clear(); - appendersLoading.clear(); - const usedAppenders = []; - Object.values(config.categories).forEach(category => { - usedAppenders.push(...category.appenders) - }); - Object.keys(config.appenders).forEach((name) => { - // dodgy hard-coding of special case for tcp-server which may not have - // any categories associated with it, but needs to be started up anyway - if (usedAppenders.includes(name) || config.appenders[name].type === 'tcp-server') { - getAppender(name, config); - } - }); -}; - -setup({ appenders: { out: { type: 'stdout' } }, categories: { default: { appenders: ['out'], level: 'trace' } } }); - -configuration.addListener((config) => { - configuration.throwExceptionIf( - config, - configuration.not(configuration.anObject(config.appenders)), - 'must have a property "appenders" of type object.' - ); - const appenderNames = Object.keys(config.appenders); - configuration.throwExceptionIf( - config, - configuration.not(appenderNames.length), - 'must define at least one appender.' - ); - - appenderNames.forEach((name) => { - configuration.throwExceptionIf( - config, - configuration.not(config.appenders[name].type), - `appender "${name}" is not valid (must be an object with property "type")` - ); - }); -}); - -configuration.addListener(setup); - -module.exports = appenders; - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)("log4js:clustering"); -const LoggingEvent = __webpack_require__(86); -const configuration = __webpack_require__(79); - -let disabled = false; -let cluster = null; -try { - cluster = __webpack_require__(88); //eslint-disable-line -} catch (e) { - debug("cluster module not present"); - disabled = true; -} - -const listeners = []; - -let pm2 = false; -let pm2InstanceVar = "NODE_APP_INSTANCE"; - -const isPM2Master = () => pm2 && process.env[pm2InstanceVar] === "0"; -const isMaster = () => disabled || cluster.isMaster || isPM2Master(); - -const sendToListeners = logEvent => { - listeners.forEach(l => l(logEvent)); -}; - -// in a multi-process node environment, worker loggers will use -// process.send -const receiver = (worker, message) => { - // prior to node v6, the worker parameter was not passed (args were message, handle) - debug("cluster message received from worker ", worker, ": ", message); - if (worker.topic && worker.data) { - message = worker; - worker = undefined; - } - if (message && message.topic && message.topic === "log4js:message") { - debug("received message: ", message.data); - const logEvent = LoggingEvent.deserialise(message.data); - sendToListeners(logEvent); - } -}; - -if (!disabled) { - configuration.addListener(config => { - // clear out the listeners, because configure has been called. - listeners.length = 0; - - ({ - pm2, - disableClustering: disabled, - pm2InstanceVar = "NODE_APP_INSTANCE" - } = config); - - debug(`clustering disabled ? ${disabled}`); - debug(`cluster.isMaster ? ${cluster && cluster.isMaster}`); - debug(`pm2 enabled ? ${pm2}`); - debug(`pm2InstanceVar = ${pm2InstanceVar}`); - debug(`process.env[${pm2InstanceVar}] = ${process.env[pm2InstanceVar]}`); - - // just in case configure is called after shutdown - if (pm2) { - process.removeListener("message", receiver); - } - if (cluster && cluster.removeListener) { - cluster.removeListener("message", receiver); - } - - if (disabled || config.disableClustering) { - debug("Not listening for cluster messages, because clustering disabled."); - } else if (isPM2Master()) { - // PM2 cluster support - // PM2 runs everything as workers - install pm2-intercom for this to work. - // we only want one of the app instances to write logs - debug("listening for PM2 broadcast messages"); - process.on("message", receiver); - } else if (cluster.isMaster) { - debug("listening for cluster messages"); - cluster.on("message", receiver); - } else { - debug("not listening for messages, because we are not a master process"); - } - }); -} - -module.exports = { - onlyOnMaster: (fn, notMaster) => (isMaster() ? fn() : notMaster), - isMaster, - send: msg => { - if (isMaster()) { - sendToListeners(msg); - } else { - if (!pm2) { - msg.cluster = { - workerId: cluster.worker.id, - worker: process.pid - }; - } - process.send({ topic: "log4js:message", data: msg.serialise() }); - } - }, - onMessage: listener => { - listeners.push(listener); - } -}; - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - -const flatted = __webpack_require__(87); -const levels = __webpack_require__(83); - -/** - * @name LoggingEvent - * @namespace Log4js - */ -class LoggingEvent { - /** - * Models a logging event. - * @constructor - * @param {string} categoryName name of category - * @param {Log4js.Level} level level of message - * @param {Array} data objects to log - * @author Seth Chisamore - */ - constructor(categoryName, level, data, context, location) { - this.startTime = new Date(); - this.categoryName = categoryName; - this.data = data; - this.level = level; - this.context = Object.assign({}, context); - this.pid = process.pid; - - if (location) { - this.functionName = location.functionName; - this.fileName = location.fileName; - this.lineNumber = location.lineNumber; - this.columnNumber = location.columnNumber; - this.callStack = location.callStack; - } - } - - serialise() { - const logData = this.data.map((e) => { - // JSON.stringify(new Error('test')) returns {}, which is not really useful for us. - // The following allows us to serialize errors correctly. - if (e && e.message && e.stack) { - e = Object.assign({ message: e.message, stack: e.stack }, e); - } - return e; - }); - this.data = logData; - return flatted.stringify(this); - } - - static deserialise(serialised) { - let event; - try { - const rehydratedEvent = flatted.parse(serialised); - rehydratedEvent.data = rehydratedEvent.data.map((e) => { - if (e && e.message && e.stack) { - const fakeError = new Error(e); - Object.keys(e).forEach((key) => { fakeError[key] = e[key]; }); - e = fakeError; - } - return e; - }); - event = new LoggingEvent( - rehydratedEvent.categoryName, - levels.getLevel(rehydratedEvent.level.levelStr), - rehydratedEvent.data, - rehydratedEvent.context - ); - event.startTime = new Date(rehydratedEvent.startTime); - event.pid = rehydratedEvent.pid; - event.cluster = rehydratedEvent.cluster; - } catch (e) { - event = new LoggingEvent( - 'log4js', - levels.ERROR, - ['Unable to parse log:', serialised, 'because: ', e] - ); - } - - return event; - } -} - -module.exports = LoggingEvent; - - -/***/ }), -/* 87 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringify", function() { return stringify; }); -var Flatted = (function (Primitive, primitive) { - - /*! - * ISC License - * - * Copyright (c) 2018, Andrea Giammarchi, @WebReflection - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE - * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ - - var Flatted = { - - parse: function parse(text, reviver) { - var input = JSON.parse(text, Primitives).map(primitives); - var value = input[0]; - var $ = reviver || noop; - var tmp = typeof value === 'object' && value ? - revive(input, new Set, value, $) : - value; - return $.call({'': tmp}, '', tmp); - }, - - stringify: function stringify(value, replacer, space) { - for (var - firstRun, - known = new Map, - input = [], - output = [], - $ = replacer && typeof replacer === typeof input ? - function (k, v) { - if (k === '' || -1 < replacer.indexOf(k)) return v; - } : - (replacer || noop), - i = +set(known, input, $.call({'': value}, '', value)), - replace = function (key, value) { - if (firstRun) { - firstRun = !firstRun; - return value; - } - var after = $.call(this, key, value); - switch (typeof after) { - case 'object': - if (after === null) return after; - case primitive: - return known.get(after) || set(known, input, after); - } - return after; - }; - i < input.length; i++ - ) { - firstRun = true; - output[i] = JSON.stringify(input[i], replace, space); - } - return '[' + output.join(',') + ']'; - } - - }; - - return Flatted; - - function noop(key, value) { - return value; - } - - function revive(input, parsed, output, $) { - return Object.keys(output).reduce( - function (output, key) { - var value = output[key]; - if (value instanceof Primitive) { - var tmp = input[value]; - if (typeof tmp === 'object' && !parsed.has(tmp)) { - parsed.add(tmp); - output[key] = $.call(output, key, revive(input, parsed, tmp, $)); - } else { - output[key] = $.call(output, key, tmp); - } - } else - output[key] = $.call(output, key, value); - return output; - }, - output - ); - } - - function set(known, input, value) { - var index = Primitive(input.push(value) - 1); - known.set(value, index); - return index; - } - - // the two kinds of primitives - // 1. the real one - // 2. the wrapped one - - function primitives(value) { - return value instanceof Primitive ? Primitive(value) : value; - } - - function Primitives(key, value) { - return typeof value === primitive ? new Primitive(value) : value; - } - -}(String, 'string')); -/* harmony default export */ __webpack_exports__["default"] = (Flatted); -var parse = Flatted.parse; -var stringify = Flatted.stringify; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports) { - -module.exports = require("cluster"); - -/***/ }), -/* 89 */ -/***/ (function(module, exports) { - -function maxFileSizeUnitTransform(maxLogSize) { - if (typeof maxLogSize === 'number' && Number.isInteger(maxLogSize)) { - return maxLogSize; - } - - const units = { - K: 1024, - M: 1024 * 1024, - G: 1024 * 1024 * 1024, - }; - const validUnit = Object.keys(units); - const unit = maxLogSize.substr(maxLogSize.length - 1).toLocaleUpperCase(); - const value = maxLogSize.substring(0, maxLogSize.length - 1).trim(); - - if (validUnit.indexOf(unit) < 0 || !Number.isInteger(Number(value))) { - throw Error(`maxLogSize: "${maxLogSize}" is invalid`); - } else { - return value * units[unit]; - } -} - -function adapter(configAdapter, config) { - const newConfig = Object.assign({}, config); - Object.keys(configAdapter).forEach((key) => { - if (newConfig[key]) { - newConfig[key] = configAdapter[key](config[key]); - } - }); - return newConfig; -} - -function fileAppenderAdapter(config) { - const configAdapter = { - maxLogSize: maxFileSizeUnitTransform - }; - return adapter(configAdapter, config); -} - -const adapters = { - file: fileAppenderAdapter, - fileSync: fileAppenderAdapter -}; - -module.exports.modifyConfig = config => (adapters[config.type] ? adapters[config.type](config) : config); - - -/***/ }), -/* 90 */ -/***/ (function(module, exports) { - -// eslint-disable-next-line no-console -const consoleLog = console.log.bind(console); - -function consoleAppender(layout, timezoneOffset) { - return (loggingEvent) => { - consoleLog(layout(loggingEvent, timezoneOffset)); - }; -} - -function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return consoleAppender(layout, config.timezoneOffset); -} - -module.exports.configure = configure; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports) { - - - -function stdoutAppender(layout, timezoneOffset) { - return (loggingEvent) => { - process.stdout.write(`${layout(loggingEvent, timezoneOffset)}\n`); - }; -} - -function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return stdoutAppender(layout, config.timezoneOffset); -} - -exports.configure = configure; - - -/***/ }), -/* 92 */ -/***/ (function(module, exports) { - - - -function stderrAppender(layout, timezoneOffset) { - return (loggingEvent) => { - process.stderr.write(`${layout(loggingEvent, timezoneOffset)}\n`); - }; -} - -function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return stderrAppender(layout, config.timezoneOffset); -} - -module.exports.configure = configure; - - -/***/ }), -/* 93 */ -/***/ (function(module, exports) { - -function logLevelFilter(minLevelString, maxLevelString, appender, levels) { - const minLevel = levels.getLevel(minLevelString); - const maxLevel = levels.getLevel(maxLevelString, levels.FATAL); - return (logEvent) => { - const eventLevel = logEvent.level; - if (eventLevel.isGreaterThanOrEqualTo(minLevel) && eventLevel.isLessThanOrEqualTo(maxLevel)) { - appender(logEvent); - } - }; -} - -function configure(config, layouts, findAppender, levels) { - const appender = findAppender(config.appender); - return logLevelFilter(config.level, config.maxLevel, appender, levels); -} - -module.exports.configure = configure; - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)('log4js:categoryFilter'); - -function categoryFilter(excludes, appender) { - if (typeof excludes === 'string') excludes = [excludes]; - return (logEvent) => { - debug(`Checking ${logEvent.categoryName} against ${excludes}`); - if (excludes.indexOf(logEvent.categoryName) === -1) { - debug('Not excluded, sending to appender'); - appender(logEvent); - } - }; -} - -function configure(config, layouts, findAppender) { - const appender = findAppender(config.appender); - return categoryFilter(config.exclude, appender); -} - -module.exports.configure = configure; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - - -const debug = __webpack_require__(68)('log4js:noLogFilter'); - -/** - * The function removes empty or null regexp from the array - * @param {string[]} regexp - * @returns {string[]} a filtered string array with not empty or null regexp - */ -function removeNullOrEmptyRegexp(regexp) { - const filtered = regexp.filter(el => ((el != null) && (el !== ''))); - return filtered; -} - -/** - * Returns a function that will exclude the events in case they match - * with the regular expressions provided - * @param {(string|string[])} filters contains the regexp that will be used for the evaluation - * @param {*} appender - * @returns {function} - */ -function noLogFilter(filters, appender) { - return (logEvent) => { - debug(`Checking data: ${logEvent.data} against filters: ${filters}`); - if (typeof filters === 'string') { - filters = [filters]; - } - filters = removeNullOrEmptyRegexp(filters); - const regex = new RegExp(filters.join('|'), 'i'); - if (filters.length === 0 - || logEvent.data.findIndex(value => regex.test(value)) < 0) { - debug('Not excluded, sending to appender'); - appender(logEvent); - } - }; -} - -function configure(config, layouts, findAppender) { - const appender = findAppender(config.appender); - return noLogFilter(config.exclude, appender); -} - -module.exports.configure = configure; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)('log4js:file'); -const path = __webpack_require__(82); -const streams = __webpack_require__(97); -const os = __webpack_require__(76); - -const eol = os.EOL; - -function openTheStream(file, fileSize, numFiles, options) { - const stream = new streams.RollingFileStream( - file, - fileSize, - numFiles, - options - ); - stream.on('error', (err) => { - console.error('log4js.fileAppender - Writing to file %s, error happened ', file, err); //eslint-disable-line - }); - stream.on('drain', () => { - process.emit("log4js:pause", false); - }); - return stream; -} - - -/** - * File Appender writing the logs to a text file. Supports rolling of logs by size. - * - * @param file file log messages will be written to - * @param layout a function that takes a logEvent and returns a string - * (defaults to basicLayout). - * @param logSize - the maximum size (in bytes) for a log file, - * if not provided then logs won't be rotated. - * @param numBackups - the number of log files to keep after logSize - * has been reached (default 5) - * @param options - options to be passed to the underlying stream - * @param timezoneOffset - optional timezone offset in minutes (default system local) - */ -function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset) { - file = path.normalize(file); - numBackups = numBackups === undefined ? 5 : numBackups; - // there has to be at least one backup if logSize has been specified - numBackups = numBackups === 0 ? 1 : numBackups; - - debug( - 'Creating file appender (', - file, ', ', - logSize, ', ', - numBackups, ', ', - options, ', ', - timezoneOffset, ')' - ); - - let writer = openTheStream(file, logSize, numBackups, options); - - const app = function (loggingEvent) { - if (options.removeColor === true) { - // eslint-disable-next-line no-control-regex - const regex = /\x1b[[0-9;]*m/g; - loggingEvent.data = loggingEvent.data.map(d => { - if (typeof d === 'string') return d.replace(regex, '') - return d - }) - } - if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, "utf8")) { - process.emit('log4js:pause', true); - } - }; - - app.reopen = function () { - writer.end(() => { writer = openTheStream(file, logSize, numBackups, options); }); - }; - - app.sighupHandler = function () { - debug('SIGHUP handler called.'); - app.reopen(); - }; - - app.shutdown = function (complete) { - process.removeListener('SIGHUP', app.sighupHandler); - writer.end('', 'utf-8', complete); - }; - - // On SIGHUP, close and reopen all files. This allows this appender to work with - // logrotate. Note that if you are using logrotate, you should not set - // `logSize`. - process.on('SIGHUP', app.sighupHandler); - - return app; -} - -function configure(config, layouts) { - let layout = layouts.basicLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - - return fileAppender( - config.filename, - layout, - config.maxLogSize, - config.backups, - config, - config.timezoneOffset - ); -} - -module.exports.configure = configure; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = { - RollingFileWriteStream: __webpack_require__(98), - RollingFileStream: __webpack_require__(146), - DateRollingFileStream: __webpack_require__(147) -}; - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)("streamroller:RollingFileWriteStream"); -const fs = __webpack_require__(99); -const path = __webpack_require__(82); -const newNow = __webpack_require__(140); -const format = __webpack_require__(141); -const { Writable } = __webpack_require__(106); -const fileNameFormatter = __webpack_require__(142); -const fileNameParser = __webpack_require__(143); -const moveAndMaybeCompressFile = __webpack_require__(144); - -/** - * RollingFileWriteStream is mainly used when writing to a file rolling by date or size. - * RollingFileWriteStream inherits from stream.Writable - */ -class RollingFileWriteStream extends Writable { - /** - * Create a RollingFileWriteStream - * @constructor - * @param {string} filePath - The file path to write. - * @param {object} options - The extra options - * @param {number} options.numToKeep - The max numbers of files to keep. - * @param {number} options.maxSize - The maxSize one file can reach. Unit is Byte. - * This should be more than 1024. The default is Number.MAX_SAFE_INTEGER. - * @param {string} options.mode - The mode of the files. The default is '0644'. Refer to stream.writable for more. - * @param {string} options.flags - The default is 'a'. Refer to stream.flags for more. - * @param {boolean} options.compress - Whether to compress backup files. - * @param {boolean} options.keepFileExt - Whether to keep the file extension. - * @param {string} options.pattern - The date string pattern in the file name. - * @param {boolean} options.alwaysIncludePattern - Whether to add date to the name of the first file. - */ - constructor(filePath, options) { - debug(`constructor: creating RollingFileWriteStream. path=${filePath}`); - super(options); - this.options = this._parseOption(options); - this.fileObject = path.parse(filePath); - if (this.fileObject.dir === "") { - this.fileObject = path.parse(path.join(process.cwd(), filePath)); - } - this.fileFormatter = fileNameFormatter({ - file: this.fileObject, - alwaysIncludeDate: this.options.alwaysIncludePattern, - needsIndex: this.options.maxSize < Number.MAX_SAFE_INTEGER, - compress: this.options.compress, - keepFileExt: this.options.keepFileExt - }); - - this.fileNameParser = fileNameParser({ - file: this.fileObject, - keepFileExt: this.options.keepFileExt, - pattern: this.options.pattern - }); - - this.state = { - currentSize: 0 - }; - - if (this.options.pattern) { - this.state.currentDate = format(this.options.pattern, newNow()); - } - - this.filename = this.fileFormatter({ - index: 0, - date: this.state.currentDate - }); - if (["a", "a+", "as", "as+"].includes(this.options.flags)) { - this._setExistingSizeAndDate(); - } - - debug( - `constructor: create new file ${this.filename}, state=${JSON.stringify( - this.state - )}` - ); - this._renewWriteStream(); - } - - _setExistingSizeAndDate() { - try { - const stats = fs.statSync(this.filename); - this.state.currentSize = stats.size; - if (this.options.pattern) { - this.state.currentDate = format(this.options.pattern, stats.mtime); - } - } catch (e) { - //file does not exist, that's fine - move along - return; - } - } - - _parseOption(rawOptions) { - const defaultOptions = { - maxSize: Number.MAX_SAFE_INTEGER, - numToKeep: Number.MAX_SAFE_INTEGER, - encoding: "utf8", - mode: parseInt("0644", 8), - flags: "a", - compress: false, - keepFileExt: false, - alwaysIncludePattern: false - }; - const options = Object.assign({}, defaultOptions, rawOptions); - if (options.maxSize <= 0) { - throw new Error(`options.maxSize (${options.maxSize}) should be > 0`); - } - if (options.numToKeep <= 0) { - throw new Error(`options.numToKeep (${options.numToKeep}) should be > 0`); - } - debug( - `_parseOption: creating stream with option=${JSON.stringify(options)}` - ); - return options; - } - - _final(callback) { - this.currentFileStream.end("", this.options.encoding, callback); - } - - _write(chunk, encoding, callback) { - this._shouldRoll().then(() => { - debug( - `_write: writing chunk. ` + - `file=${this.currentFileStream.path} ` + - `state=${JSON.stringify(this.state)} ` + - `chunk=${chunk}` - ); - this.currentFileStream.write(chunk, encoding, e => { - this.state.currentSize += chunk.length; - callback(e); - }); - }); - } - - async _shouldRoll() { - if (this._dateChanged() || this._tooBig()) { - debug( - `_shouldRoll: rolling because dateChanged? ${this._dateChanged()} or tooBig? ${this._tooBig()}` - ); - await this._roll(); - } - } - - _dateChanged() { - return ( - this.state.currentDate && - this.state.currentDate !== format(this.options.pattern, newNow()) - ); - } - - _tooBig() { - return this.state.currentSize >= this.options.maxSize; - } - - _roll() { - debug(`_roll: closing the current stream`); - return new Promise((resolve, reject) => { - this.currentFileStream.end("", this.options.encoding, () => { - this._moveOldFiles() - .then(resolve) - .catch(reject); - }); - }); - } - - async _moveOldFiles() { - const files = await this._getExistingFiles(); - const todaysFiles = this.state.currentDate - ? files.filter(f => f.date === this.state.currentDate) - : files; - for (let i = todaysFiles.length; i >= 0; i--) { - debug(`_moveOldFiles: i = ${i}`); - const sourceFilePath = this.fileFormatter({ - date: this.state.currentDate, - index: i - }); - const targetFilePath = this.fileFormatter({ - date: this.state.currentDate, - index: i + 1 - }); - - await moveAndMaybeCompressFile( - sourceFilePath, - targetFilePath, - this.options.compress && i === 0 - ); - } - - this.state.currentSize = 0; - this.state.currentDate = this.state.currentDate - ? format(this.options.pattern, newNow()) - : null; - debug( - `_moveOldFiles: finished rolling files. state=${JSON.stringify( - this.state - )}` - ); - this._renewWriteStream(); - // wait for the file to be open before cleaning up old ones, - // otherwise the daysToKeep calculations can be off - await new Promise((resolve, reject) => { - this.currentFileStream.write("", "utf8", () => { - this._clean() - .then(resolve) - .catch(reject); - }); - }); - } - - // Sorted from the oldest to the latest - async _getExistingFiles() { - const files = await fs.readdir(this.fileObject.dir).catch(() => []); - - debug(`_getExistingFiles: files=${files}`); - const existingFileDetails = files - .map(n => this.fileNameParser(n)) - .filter(n => n); - - const getKey = n => - (n.timestamp ? n.timestamp : newNow().getTime()) - n.index; - existingFileDetails.sort((a, b) => getKey(a) - getKey(b)); - - return existingFileDetails; - } - - _renewWriteStream() { - fs.ensureDirSync(this.fileObject.dir); - const filePath = this.fileFormatter({ - date: this.state.currentDate, - index: 0 - }); - const ops = { - flags: this.options.flags, - encoding: this.options.encoding, - mode: this.options.mode - }; - this.currentFileStream = fs.createWriteStream(filePath, ops); - this.currentFileStream.on("error", e => { - this.emit("error", e); - }); - } - - async _clean() { - const existingFileDetails = await this._getExistingFiles(); - debug( - `_clean: numToKeep = ${this.options.numToKeep}, existingFiles = ${existingFileDetails.length}` - ); - debug("_clean: existing files are: ", existingFileDetails); - if (this._tooManyFiles(existingFileDetails.length)) { - const fileNamesToRemove = existingFileDetails - .slice(0, existingFileDetails.length - this.options.numToKeep - 1) - .map(f => path.format({ dir: this.fileObject.dir, base: f.filename })); - await deleteFiles(fileNamesToRemove); - } - } - - _tooManyFiles(numFiles) { - return this.options.numToKeep > 0 && numFiles > this.options.numToKeep; - } -} - -const deleteFiles = fileNames => { - debug(`deleteFiles: files to delete: ${fileNames}`); - return Promise.all(fileNames.map(f => fs.unlink(f).catch((e) => { - debug(`deleteFiles: error when unlinking ${f}, ignoring. Error was ${e}`); - }))); -}; - -module.exports = RollingFileWriteStream; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = Object.assign( - {}, - // Export promiseified graceful-fs: - __webpack_require__(100), - // Export extra methods: - __webpack_require__(109), - __webpack_require__(118), - __webpack_require__(121), - __webpack_require__(124), - __webpack_require__(130), - __webpack_require__(111), - __webpack_require__(135), - __webpack_require__(137), - __webpack_require__(139), - __webpack_require__(120), - __webpack_require__(122) -) - -// Export fs.promises as a getter property so that we don't trigger -// ExperimentalWarning before fs.promises is actually accessed. -const fs = __webpack_require__(66) -if (Object.getOwnPropertyDescriptor(fs, 'promises')) { - Object.defineProperty(module.exports, 'promises', { - get () { return fs.promises } - }) -} - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// This is adapted from https://github.com/normalize/mz -// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors -const u = __webpack_require__(101).fromCallback -const fs = __webpack_require__(102) - -const api = [ - 'access', - 'appendFile', - 'chmod', - 'chown', - 'close', - 'copyFile', - 'fchmod', - 'fchown', - 'fdatasync', - 'fstat', - 'fsync', - 'ftruncate', - 'futimes', - 'lchown', - 'lchmod', - 'link', - 'lstat', - 'mkdir', - 'mkdtemp', - 'open', - 'readFile', - 'readdir', - 'readlink', - 'realpath', - 'rename', - 'rmdir', - 'stat', - 'symlink', - 'truncate', - 'unlink', - 'utimes', - 'writeFile' -].filter(key => { - // Some commands are not available on some systems. Ex: - // fs.copyFile was added in Node.js v8.5.0 - // fs.mkdtemp was added in Node.js v5.10.0 - // fs.lchown is not available on at least some Linux - return typeof fs[key] === 'function' -}) - -// Export all keys: -Object.keys(fs).forEach(key => { - if (key === 'promises') { - // fs.promises is a getter property that triggers ExperimentalWarning - // Don't re-export it here, the getter is defined in "lib/index.js" - return - } - exports[key] = fs[key] -}) - -// Universalify async methods: -api.forEach(method => { - exports[method] = u(fs[method]) -}) - -// We differ from mz/fs in that we still ship the old, broken, fs.exists() -// since we are a drop-in replacement for the native module -exports.exists = function (filename, callback) { - if (typeof callback === 'function') { - return fs.exists(filename, callback) - } - return new Promise(resolve => { - return fs.exists(filename, resolve) - }) -} - -// fs.read() & fs.write need special treatment due to multiple callback args - -exports.read = function (fd, buffer, offset, length, position, callback) { - if (typeof callback === 'function') { - return fs.read(fd, buffer, offset, length, position, callback) - } - return new Promise((resolve, reject) => { - fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { - if (err) return reject(err) - resolve({ bytesRead, buffer }) - }) - }) -} - -// Function signature can be -// fs.write(fd, buffer[, offset[, length[, position]]], callback) -// OR -// fs.write(fd, string[, position[, encoding]], callback) -// We need to handle both cases, so we use ...args -exports.write = function (fd, buffer, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.write(fd, buffer, ...args) - } - - return new Promise((resolve, reject) => { - fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { - if (err) return reject(err) - resolve({ bytesWritten, buffer }) - }) - }) -} - -// fs.realpath.native only available in Node v9.2+ -if (typeof fs.realpath.native === 'function') { - exports.realpath.native = u(fs.realpath.native) -} - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.fromCallback = function (fn) { - return Object.defineProperty(function () { - if (typeof arguments[arguments.length - 1] === 'function') fn.apply(this, arguments) - else { - return new Promise((resolve, reject) => { - arguments[arguments.length] = (err, res) => { - if (err) return reject(err) - resolve(res) - } - arguments.length++ - fn.apply(this, arguments) - }) - } - }, 'name', { value: fn.name }) -} - -exports.fromPromise = function (fn) { - return Object.defineProperty(function () { - const cb = arguments[arguments.length - 1] - if (typeof cb !== 'function') return fn.apply(this, arguments) - else fn.apply(this, arguments).then(r => cb(null, r), cb) - }, 'name', { value: fn.name }) -} - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -var fs = __webpack_require__(66) -var polyfills = __webpack_require__(103) -var legacy = __webpack_require__(105) -var clone = __webpack_require__(107) - -var util = __webpack_require__(74) - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} - -function noop () {} - -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - retry() - } - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) - - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - retry() - } - - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) - - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __webpack_require__(108).equal(fs[gracefulQueue].length, 0) - }) - } -} - -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} - -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} - -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$readFile(path, options, cb) - - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$writeFile(path, data, options, cb) - - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$appendFile(path, data, options, cb) - - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) - - return go$readdir(args) - - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() - - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) - - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - } - } - - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } - - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } - - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } - - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) - - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) - - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() - - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } - - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } - - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } - - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) -} - -function retry () { - var elem = fs[gracefulQueue].shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } -} - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -var constants = __webpack_require__(104) - -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} - -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} - -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) - - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) - - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) - - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) - - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } - - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. - - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } - - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - - // This ensures `util.promisify` works as it does for native `fs.read`. - read.__proto__ = fs$read - return read - })(fs.read) - - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } - - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } - - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } - } - - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } - - return false - } -} - - -/***/ }), -/* 104 */ -/***/ (function(module, exports) { - -module.exports = require("constants"); - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -var Stream = __webpack_require__(106).Stream - -module.exports = legacy - -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - Stream.call(this); - - var self = this; - - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; - } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} - - -/***/ }), -/* 106 */ -/***/ (function(module, exports) { - -module.exports = require("stream"); - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = clone - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy -} - - -/***/ }), -/* 108 */ -/***/ (function(module, exports) { - -module.exports = require("assert"); - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = { - copySync: __webpack_require__(110) -} - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const mkdirpSync = __webpack_require__(111).mkdirsSync -const utimesSync = __webpack_require__(115).utimesMillisSync -const stat = __webpack_require__(116) - -function copySync (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts } - } - - opts = opts || {} - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) - } - - const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy') - stat.checkParentPathsSync(src, srcStat, dest, 'copy') - return handleFilterAndCopy(destStat, src, dest, opts) -} - -function handleFilterAndCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path.dirname(dest) - if (!fs.existsSync(destParent)) mkdirpSync(destParent) - return startCopy(destStat, src, dest, opts) -} - -function startCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - return getStats(destStat, src, dest, opts) -} - -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs.statSync : fs.lstatSync - const srcStat = statSync(src) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) -} - -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} - -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs.unlinkSync(dest) - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} - -function copyFile (srcStat, src, dest, opts) { - if (typeof fs.copyFileSync === 'function') { - fs.copyFileSync(src, dest) - fs.chmodSync(dest, srcStat.mode) - if (opts.preserveTimestamps) { - return utimesSync(dest, srcStat.atime, srcStat.mtime) - } - return - } - return copyFileFallback(srcStat, src, dest, opts) -} - -function copyFileFallback (srcStat, src, dest, opts) { - const BUF_LENGTH = 64 * 1024 - const _buff = __webpack_require__(117)(BUF_LENGTH) - - const fdr = fs.openSync(src, 'r') - const fdw = fs.openSync(dest, 'w', srcStat.mode) - let pos = 0 - - while (pos < srcStat.size) { - const bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos) - fs.writeSync(fdw, _buff, 0, bytesRead) - pos += bytesRead - } - - if (opts.preserveTimestamps) fs.futimesSync(fdw, srcStat.atime, srcStat.mtime) - - fs.closeSync(fdr) - fs.closeSync(fdw) -} - -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) return mkDirAndCopy(srcStat, src, dest, opts) - if (destStat && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - return copyDir(src, dest, opts) -} - -function mkDirAndCopy (srcStat, src, dest, opts) { - fs.mkdirSync(dest) - copyDir(src, dest, opts) - return fs.chmodSync(dest, srcStat.mode) -} - -function copyDir (src, dest, opts) { - fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) -} - -function copyDirItem (item, src, dest, opts) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy') - return startCopy(destStat, srcItem, destItem, opts) -} - -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs.readlinkSync(src) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest - try { - resolvedDest = fs.readlinkSync(dest) - } catch (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) - throw err - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } - - // prevent copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - return copyLink(resolvedSrc, dest) - } -} - -function copyLink (resolvedSrc, dest) { - fs.unlinkSync(dest) - return fs.symlinkSync(resolvedSrc, dest) -} - -module.exports = copySync - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const u = __webpack_require__(101).fromCallback -const mkdirs = u(__webpack_require__(112)) -const mkdirsSync = __webpack_require__(114) - -module.exports = { - mkdirs, - mkdirsSync, - // alias - mkdirp: mkdirs, - mkdirpSync: mkdirsSync, - ensureDir: mkdirs, - ensureDirSync: mkdirsSync -} - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const invalidWin32Path = __webpack_require__(113).invalidWin32Path - -const o777 = parseInt('0777', 8) - -function mkdirs (p, opts, callback, made) { - if (typeof opts === 'function') { - callback = opts - opts = {} - } else if (!opts || typeof opts !== 'object') { - opts = { mode: opts } - } - - if (process.platform === 'win32' && invalidWin32Path(p)) { - const errInval = new Error(p + ' contains invalid WIN32 path characters.') - errInval.code = 'EINVAL' - return callback(errInval) - } - - let mode = opts.mode - const xfs = opts.fs || fs - - if (mode === undefined) { - mode = o777 & (~process.umask()) - } - if (!made) made = null - - callback = callback || function () {} - p = path.resolve(p) - - xfs.mkdir(p, mode, er => { - if (!er) { - made = made || p - return callback(null, made) - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return callback(er) - mkdirs(path.dirname(p), opts, (er, made) => { - if (er) callback(er, made) - else mkdirs(p, opts, callback, made) - }) - break - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, (er2, stat) => { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) callback(er, made) - else callback(null, made) - }) - break - } - }) -} - -module.exports = mkdirs - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const path = __webpack_require__(82) - -// get drive on windows -function getRootPath (p) { - p = path.normalize(path.resolve(p)).split(path.sep) - if (p.length > 0) return p[0] - return null -} - -// http://stackoverflow.com/a/62888/10333 contains more accurate -// TODO: expand to include the rest -const INVALID_PATH_CHARS = /[<>:"|?*]/ - -function invalidWin32Path (p) { - const rp = getRootPath(p) - p = p.replace(rp, '') - return INVALID_PATH_CHARS.test(p) -} - -module.exports = { - getRootPath, - invalidWin32Path -} - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const invalidWin32Path = __webpack_require__(113).invalidWin32Path - -const o777 = parseInt('0777', 8) - -function mkdirsSync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts } - } - - let mode = opts.mode - const xfs = opts.fs || fs - - if (process.platform === 'win32' && invalidWin32Path(p)) { - const errInval = new Error(p + ' contains invalid WIN32 path characters.') - errInval.code = 'EINVAL' - throw errInval - } - - if (mode === undefined) { - mode = o777 & (~process.umask()) - } - if (!made) made = null - - p = path.resolve(p) - - try { - xfs.mkdirSync(p, mode) - made = made || p - } catch (err0) { - if (err0.code === 'ENOENT') { - if (path.dirname(p) === p) throw err0 - made = mkdirsSync(path.dirname(p), opts, made) - mkdirsSync(p, opts, made) - } else { - // In the case of any other error, just see if there's a dir there - // already. If so, then hooray! If not, then something is borked. - let stat - try { - stat = xfs.statSync(p) - } catch (err1) { - throw err0 - } - if (!stat.isDirectory()) throw err0 - } - } - - return made -} - -module.exports = mkdirsSync - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const os = __webpack_require__(76) -const path = __webpack_require__(82) - -// HFS, ext{2,3}, FAT do not, Node.js v0.10 does not -function hasMillisResSync () { - let tmpfile = path.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2)) - tmpfile = path.join(os.tmpdir(), tmpfile) - - // 550 millis past UNIX epoch - const d = new Date(1435410243862) - fs.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141') - const fd = fs.openSync(tmpfile, 'r+') - fs.futimesSync(fd, d, d) - fs.closeSync(fd) - return fs.statSync(tmpfile).mtime > 1435410243000 -} - -function hasMillisRes (callback) { - let tmpfile = path.join('millis-test' + Date.now().toString() + Math.random().toString().slice(2)) - tmpfile = path.join(os.tmpdir(), tmpfile) - - // 550 millis past UNIX epoch - const d = new Date(1435410243862) - fs.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => { - if (err) return callback(err) - fs.open(tmpfile, 'r+', (err, fd) => { - if (err) return callback(err) - fs.futimes(fd, d, d, err => { - if (err) return callback(err) - fs.close(fd, err => { - if (err) return callback(err) - fs.stat(tmpfile, (err, stats) => { - if (err) return callback(err) - callback(null, stats.mtime > 1435410243000) - }) - }) - }) - }) - }) -} - -function timeRemoveMillis (timestamp) { - if (typeof timestamp === 'number') { - return Math.floor(timestamp / 1000) * 1000 - } else if (timestamp instanceof Date) { - return new Date(Math.floor(timestamp.getTime() / 1000) * 1000) - } else { - throw new Error('fs-extra: timeRemoveMillis() unknown parameter type') - } -} - -function utimesMillis (path, atime, mtime, callback) { - // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) - fs.open(path, 'r+', (err, fd) => { - if (err) return callback(err) - fs.futimes(fd, atime, mtime, futimesErr => { - fs.close(fd, closeErr => { - if (callback) callback(futimesErr || closeErr) - }) - }) - }) -} - -function utimesMillisSync (path, atime, mtime) { - const fd = fs.openSync(path, 'r+') - fs.futimesSync(fd, atime, mtime) - return fs.closeSync(fd) -} - -module.exports = { - hasMillisRes, - hasMillisResSync, - timeRemoveMillis, - utimesMillis, - utimesMillisSync -} - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) - -const NODE_VERSION_MAJOR_WITH_BIGINT = 10 -const NODE_VERSION_MINOR_WITH_BIGINT = 5 -const NODE_VERSION_PATCH_WITH_BIGINT = 0 -const nodeVersion = process.versions.node.split('.') -const nodeVersionMajor = Number.parseInt(nodeVersion[0], 10) -const nodeVersionMinor = Number.parseInt(nodeVersion[1], 10) -const nodeVersionPatch = Number.parseInt(nodeVersion[2], 10) - -function nodeSupportsBigInt () { - if (nodeVersionMajor > NODE_VERSION_MAJOR_WITH_BIGINT) { - return true - } else if (nodeVersionMajor === NODE_VERSION_MAJOR_WITH_BIGINT) { - if (nodeVersionMinor > NODE_VERSION_MINOR_WITH_BIGINT) { - return true - } else if (nodeVersionMinor === NODE_VERSION_MINOR_WITH_BIGINT) { - if (nodeVersionPatch >= NODE_VERSION_PATCH_WITH_BIGINT) { - return true - } - } - } - return false -} - -function getStats (src, dest, cb) { - if (nodeSupportsBigInt()) { - fs.stat(src, { bigint: true }, (err, srcStat) => { - if (err) return cb(err) - fs.stat(dest, { bigint: true }, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb(null, { srcStat, destStat: null }) - return cb(err) - } - return cb(null, { srcStat, destStat }) - }) - }) - } else { - fs.stat(src, (err, srcStat) => { - if (err) return cb(err) - fs.stat(dest, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb(null, { srcStat, destStat: null }) - return cb(err) - } - return cb(null, { srcStat, destStat }) - }) - }) - } -} - -function getStatsSync (src, dest) { - let srcStat, destStat - if (nodeSupportsBigInt()) { - srcStat = fs.statSync(src, { bigint: true }) - } else { - srcStat = fs.statSync(src) - } - try { - if (nodeSupportsBigInt()) { - destStat = fs.statSync(dest, { bigint: true }) - } else { - destStat = fs.statSync(dest) - } - } catch (err) { - if (err.code === 'ENOENT') return { srcStat, destStat: null } - throw err - } - return { srcStat, destStat } -} - -function checkPaths (src, dest, funcName, cb) { - getStats(src, dest, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - if (destStat && destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error('Source and destination must not be the same.')) - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return cb(null, { srcStat, destStat }) - }) -} - -function checkPathsSync (src, dest, funcName) { - const { srcStat, destStat } = getStatsSync(src, dest) - if (destStat && destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - return { srcStat, destStat } -} - -// recursively check if dest parent is a subdirectory of src. -// It works for all file types including symlinks since it -// checks the src and dest inodes. It starts from the deepest -// parent and stops once it reaches the src parent or the root path. -function checkParentPaths (src, srcStat, dest, funcName, cb) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() - if (nodeSupportsBigInt()) { - fs.stat(destParent, { bigint: true }, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb() - return cb(err) - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return checkParentPaths(src, srcStat, destParent, funcName, cb) - }) - } else { - fs.stat(destParent, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb() - return cb(err) - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return checkParentPaths(src, srcStat, destParent, funcName, cb) - }) - } -} - -function checkParentPathsSync (src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return - let destStat - try { - if (nodeSupportsBigInt()) { - destStat = fs.statSync(destParent, { bigint: true }) - } else { - destStat = fs.statSync(destParent) - } - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - throw new Error(errMsg(src, dest, funcName)) - } - return checkParentPathsSync(src, srcStat, destParent, funcName) -} - -// return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = path.resolve(src).split(path.sep).filter(i => i) - const destArr = path.resolve(dest).split(path.sep).filter(i => i) - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) -} - -function errMsg (src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` -} - -module.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir -} - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* eslint-disable node/no-deprecated-api */ -module.exports = function (size) { - if (typeof Buffer.allocUnsafe === 'function') { - try { - return Buffer.allocUnsafe(size) - } catch (e) { - return new Buffer(size) - } - } - return new Buffer(size) -} - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -module.exports = { - copy: u(__webpack_require__(119)) -} - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const mkdirp = __webpack_require__(111).mkdirs -const pathExists = __webpack_require__(120).pathExists -const utimes = __webpack_require__(115).utimesMillis -const stat = __webpack_require__(116) - -function copy (src, dest, opts, cb) { - if (typeof opts === 'function' && !cb) { - cb = opts - opts = {} - } else if (typeof opts === 'function') { - opts = { filter: opts } - } - - cb = cb || function () {} - opts = opts || {} - - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) - } - - stat.checkPaths(src, dest, 'copy', (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'copy', err => { - if (err) return cb(err) - if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) - return checkParentDir(destStat, src, dest, opts, cb) - }) - }) -} - -function checkParentDir (destStat, src, dest, opts, cb) { - const destParent = path.dirname(dest) - pathExists(destParent, (err, dirExists) => { - if (err) return cb(err) - if (dirExists) return startCopy(destStat, src, dest, opts, cb) - mkdirp(destParent, err => { - if (err) return cb(err) - return startCopy(destStat, src, dest, opts, cb) - }) - }) -} - -function handleFilter (onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then(include => { - if (include) return onInclude(destStat, src, dest, opts, cb) - return cb() - }, error => cb(error)) -} - -function startCopy (destStat, src, dest, opts, cb) { - if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) - return getStats(destStat, src, dest, opts, cb) -} - -function getStats (destStat, src, dest, opts, cb) { - const stat = opts.dereference ? fs.stat : fs.lstat - stat(src, (err, srcStat) => { - if (err) return cb(err) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) - }) -} - -function onFile (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return copyFile(srcStat, src, dest, opts, cb) - return mayCopyFile(srcStat, src, dest, opts, cb) -} - -function mayCopyFile (srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs.unlink(dest, err => { - if (err) return cb(err) - return copyFile(srcStat, src, dest, opts, cb) - }) - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)) - } else return cb() -} - -function copyFile (srcStat, src, dest, opts, cb) { - if (typeof fs.copyFile === 'function') { - return fs.copyFile(src, dest, err => { - if (err) return cb(err) - return setDestModeAndTimestamps(srcStat, dest, opts, cb) - }) - } - return copyFileFallback(srcStat, src, dest, opts, cb) -} - -function copyFileFallback (srcStat, src, dest, opts, cb) { - const rs = fs.createReadStream(src) - rs.on('error', err => cb(err)).once('open', () => { - const ws = fs.createWriteStream(dest, { mode: srcStat.mode }) - ws.on('error', err => cb(err)) - .on('open', () => rs.pipe(ws)) - .once('close', () => setDestModeAndTimestamps(srcStat, dest, opts, cb)) - }) -} - -function setDestModeAndTimestamps (srcStat, dest, opts, cb) { - fs.chmod(dest, srcStat.mode, err => { - if (err) return cb(err) - if (opts.preserveTimestamps) { - return utimes(dest, srcStat.atime, srcStat.mtime, cb) - } - return cb() - }) -} - -function onDir (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return mkDirAndCopy(srcStat, src, dest, opts, cb) - if (destStat && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) - } - return copyDir(src, dest, opts, cb) -} - -function mkDirAndCopy (srcStat, src, dest, opts, cb) { - fs.mkdir(dest, err => { - if (err) return cb(err) - copyDir(src, dest, opts, err => { - if (err) return cb(err) - return fs.chmod(dest, srcStat.mode, cb) - }) - }) -} - -function copyDir (src, dest, opts, cb) { - fs.readdir(src, (err, items) => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) -} - -function copyDirItems (items, src, dest, opts, cb) { - const item = items.pop() - if (!item) return cb() - return copyDirItem(items, item, src, dest, opts, cb) -} - -function copyDirItem (items, item, src, dest, opts, cb) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => { - if (err) return cb(err) - const { destStat } = stats - startCopy(destStat, srcItem, destItem, opts, err => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) - }) -} - -function onLink (destStat, src, dest, opts, cb) { - fs.readlink(src, (err, resolvedSrc) => { - if (err) return cb(err) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlink(resolvedSrc, dest, cb) - } else { - fs.readlink(dest, (err, resolvedDest) => { - if (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) - return cb(err) - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) - } - - // do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) - } - return copyLink(resolvedSrc, dest, cb) - }) - } - }) -} - -function copyLink (resolvedSrc, dest, cb) { - fs.unlink(dest, err => { - if (err) return cb(err) - return fs.symlink(resolvedSrc, dest, cb) - }) -} - -module.exports = copy - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const u = __webpack_require__(101).fromPromise -const fs = __webpack_require__(100) - -function pathExists (path) { - return fs.access(path).then(() => true).catch(() => false) -} - -module.exports = { - pathExists: u(pathExists), - pathExistsSync: fs.existsSync -} - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const mkdir = __webpack_require__(111) -const remove = __webpack_require__(122) - -const emptyDir = u(function emptyDir (dir, callback) { - callback = callback || function () {} - fs.readdir(dir, (err, items) => { - if (err) return mkdir.mkdirs(dir, callback) - - items = items.map(item => path.join(dir, item)) - - deleteItem() - - function deleteItem () { - const item = items.pop() - if (!item) return callback() - remove.remove(item, err => { - if (err) return callback(err) - deleteItem() - }) - } - }) -}) - -function emptyDirSync (dir) { - let items - try { - items = fs.readdirSync(dir) - } catch (err) { - return mkdir.mkdirsSync(dir) - } - - items.forEach(item => { - item = path.join(dir, item) - remove.removeSync(item) - }) -} - -module.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir -} - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const rimraf = __webpack_require__(123) - -module.exports = { - remove: u(rimraf), - removeSync: rimraf.sync -} - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const assert = __webpack_require__(108) - -const isWindows = (process.platform === 'win32') - -function defaults (options) { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 -} - -function rimraf (p, options, cb) { - let busyTries = 0 - - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && - busyTries < options.maxBusyTries) { - busyTries++ - const time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), time) - } - - // already gone - if (er.code === 'ENOENT') er = null - } - - cb(er) - }) -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === 'ENOENT') { - return cb(null) - } - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === 'EPERM' && isWindows) { - return fixWinEPERM(p, options, er, cb) - } - - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb) - } - - options.unlink(p, er => { - if (er) { - if (er.code === 'ENOENT') { - return cb(null) - } - if (er.code === 'EPERM') { - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - } - if (er.code === 'EISDIR') { - return rmdir(p, options, er, cb) - } - } - return cb(er) - }) - }) -} - -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) { - assert(er instanceof Error) - } - - options.chmod(p, 0o666, er2 => { - if (er2) { - cb(er2.code === 'ENOENT' ? null : er) - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === 'ENOENT' ? null : er) - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb) - } else { - options.unlink(p, cb) - } - }) - } - }) -} - -function fixWinEPERMSync (p, options, er) { - let stats - - assert(p) - assert(options) - if (er) { - assert(er instanceof Error) - } - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === 'ENOENT') { - return - } else { - throw er - } - } - - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === 'ENOENT') { - return - } else { - throw er - } - } - - if (stats.isDirectory()) { - rmdirSync(p, options, er) - } else { - options.unlinkSync(p) - } -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) { - assert(originalEr instanceof Error) - } - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { - rmkids(p, options, cb) - } else if (er && er.code === 'ENOTDIR') { - cb(originalEr) - } else { - cb(er) - } - }) -} - -function rmkids (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, (er, files) => { - if (er) return cb(er) - - let n = files.length - let errState - - if (n === 0) return options.rmdir(p, cb) - - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) { - return - } - if (er) return cb(errState = er) - if (--n === 0) { - options.rmdir(p, cb) - } - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - let st - - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === 'ENOENT') { - return - } - - // Windows can EPERM on stat. Life is suffering. - if (er.code === 'EPERM' && isWindows) { - fixWinEPERMSync(p, options, er) - } - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) { - rmdirSync(p, options, null) - } else { - options.unlinkSync(p) - } - } catch (er) { - if (er.code === 'ENOENT') { - return - } else if (er.code === 'EPERM') { - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - } else if (er.code !== 'EISDIR') { - throw er - } - rmdirSync(p, options, er) - } -} - -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) { - assert(originalEr instanceof Error) - } - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === 'ENOTDIR') { - throw originalEr - } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { - rmkidsSync(p, options) - } else if (er.code !== 'ENOENT') { - throw er - } - } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - if (isWindows) { - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const startTime = Date.now() - do { - try { - const ret = options.rmdirSync(p, options) - return ret - } catch (er) { } - } while (Date.now() - startTime < 500) // give up after 500ms - } else { - const ret = options.rmdirSync(p, options) - return ret - } -} - -module.exports = rimraf -rimraf.sync = rimrafSync - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const file = __webpack_require__(125) -const link = __webpack_require__(126) -const symlink = __webpack_require__(127) - -module.exports = { - // file - createFile: file.createFile, - createFileSync: file.createFileSync, - ensureFile: file.createFile, - ensureFileSync: file.createFileSync, - // link - createLink: link.createLink, - createLinkSync: link.createLinkSync, - ensureLink: link.createLink, - ensureLinkSync: link.createLinkSync, - // symlink - createSymlink: symlink.createSymlink, - createSymlinkSync: symlink.createSymlinkSync, - ensureSymlink: symlink.createSymlink, - ensureSymlinkSync: symlink.createSymlinkSync -} - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const path = __webpack_require__(82) -const fs = __webpack_require__(102) -const mkdir = __webpack_require__(111) -const pathExists = __webpack_require__(120).pathExists - -function createFile (file, callback) { - function makeFile () { - fs.writeFile(file, '', err => { - if (err) return callback(err) - callback() - }) - } - - fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err - if (!err && stats.isFile()) return callback() - const dir = path.dirname(file) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return makeFile() - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeFile() - }) - }) - }) -} - -function createFileSync (file) { - let stats - try { - stats = fs.statSync(file) - } catch (e) {} - if (stats && stats.isFile()) return - - const dir = path.dirname(file) - if (!fs.existsSync(dir)) { - mkdir.mkdirsSync(dir) - } - - fs.writeFileSync(file, '') -} - -module.exports = { - createFile: u(createFile), - createFileSync -} - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const path = __webpack_require__(82) -const fs = __webpack_require__(102) -const mkdir = __webpack_require__(111) -const pathExists = __webpack_require__(120).pathExists - -function createLink (srcpath, dstpath, callback) { - function makeLink (srcpath, dstpath) { - fs.link(srcpath, dstpath, err => { - if (err) return callback(err) - callback(null) - }) - } - - pathExists(dstpath, (err, destinationExists) => { - if (err) return callback(err) - if (destinationExists) return callback(null) - fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureLink') - return callback(err) - } - - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return makeLink(srcpath, dstpath) - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeLink(srcpath, dstpath) - }) - }) - }) - }) -} - -function createLinkSync (srcpath, dstpath) { - const destinationExists = fs.existsSync(dstpath) - if (destinationExists) return undefined - - try { - fs.lstatSync(srcpath) - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink') - throw err - } - - const dir = path.dirname(dstpath) - const dirExists = fs.existsSync(dir) - if (dirExists) return fs.linkSync(srcpath, dstpath) - mkdir.mkdirsSync(dir) - - return fs.linkSync(srcpath, dstpath) -} - -module.exports = { - createLink: u(createLink), - createLinkSync -} - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const path = __webpack_require__(82) -const fs = __webpack_require__(102) -const _mkdirs = __webpack_require__(111) -const mkdirs = _mkdirs.mkdirs -const mkdirsSync = _mkdirs.mkdirsSync - -const _symlinkPaths = __webpack_require__(128) -const symlinkPaths = _symlinkPaths.symlinkPaths -const symlinkPathsSync = _symlinkPaths.symlinkPathsSync - -const _symlinkType = __webpack_require__(129) -const symlinkType = _symlinkType.symlinkType -const symlinkTypeSync = _symlinkType.symlinkTypeSync - -const pathExists = __webpack_require__(120).pathExists - -function createSymlink (srcpath, dstpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - - pathExists(dstpath, (err, destinationExists) => { - if (err) return callback(err) - if (destinationExists) return callback(null) - symlinkPaths(srcpath, dstpath, (err, relative) => { - if (err) return callback(err) - srcpath = relative.toDst - symlinkType(relative.toCwd, type, (err, type) => { - if (err) return callback(err) - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) - mkdirs(dir, err => { - if (err) return callback(err) - fs.symlink(srcpath, dstpath, type, callback) - }) - }) - }) - }) - }) -} - -function createSymlinkSync (srcpath, dstpath, type) { - const destinationExists = fs.existsSync(dstpath) - if (destinationExists) return undefined - - const relative = symlinkPathsSync(srcpath, dstpath) - srcpath = relative.toDst - type = symlinkTypeSync(relative.toCwd, type) - const dir = path.dirname(dstpath) - const exists = fs.existsSync(dir) - if (exists) return fs.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir) - return fs.symlinkSync(srcpath, dstpath, type) -} - -module.exports = { - createSymlink: u(createSymlink), - createSymlinkSync -} - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const path = __webpack_require__(82) -const fs = __webpack_require__(102) -const pathExists = __webpack_require__(120).pathExists - -/** - * Function that returns two types of paths, one relative to symlink, and one - * relative to the current working directory. Checks if path is absolute or - * relative. If the path is relative, this function checks if the path is - * relative to symlink or relative to current working directory. This is an - * initiative to find a smarter `srcpath` to supply when building symlinks. - * This allows you to determine which path to use out of one of three possible - * types of source paths. The first is an absolute path. This is detected by - * `path.isAbsolute()`. When an absolute path is provided, it is checked to - * see if it exists. If it does it's used, if not an error is returned - * (callback)/ thrown (sync). The other two options for `srcpath` are a - * relative url. By default Node's `fs.symlink` works by creating a symlink - * using `dstpath` and expects the `srcpath` to be relative to the newly - * created symlink. If you provide a `srcpath` that does not exist on the file - * system it results in a broken symlink. To minimize this, the function - * checks to see if the 'relative to symlink' source file exists, and if it - * does it will use it. If it does not, it checks if there's a file that - * exists that is relative to the current working directory, if does its used. - * This preserves the expectations of the original fs.symlink spec and adds - * the ability to pass in `relative to current working direcotry` paths. - */ - -function symlinkPaths (srcpath, dstpath, callback) { - if (path.isAbsolute(srcpath)) { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - 'toCwd': srcpath, - 'toDst': srcpath - }) - }) - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - return pathExists(relativeToDst, (err, exists) => { - if (err) return callback(err) - if (exists) { - return callback(null, { - 'toCwd': relativeToDst, - 'toDst': srcpath - }) - } else { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - 'toCwd': srcpath, - 'toDst': path.relative(dstdir, srcpath) - }) - }) - } - }) - } -} - -function symlinkPathsSync (srcpath, dstpath) { - let exists - if (path.isAbsolute(srcpath)) { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('absolute srcpath does not exist') - return { - 'toCwd': srcpath, - 'toDst': srcpath - } - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - exists = fs.existsSync(relativeToDst) - if (exists) { - return { - 'toCwd': relativeToDst, - 'toDst': srcpath - } - } else { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('relative srcpath does not exist') - return { - 'toCwd': srcpath, - 'toDst': path.relative(dstdir, srcpath) - } - } - } -} - -module.exports = { - symlinkPaths, - symlinkPathsSync -} - - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) - -function symlinkType (srcpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - if (type) return callback(null, type) - fs.lstat(srcpath, (err, stats) => { - if (err) return callback(null, 'file') - type = (stats && stats.isDirectory()) ? 'dir' : 'file' - callback(null, type) - }) -} - -function symlinkTypeSync (srcpath, type) { - let stats - - if (type) return type - try { - stats = fs.lstatSync(srcpath) - } catch (e) { - return 'file' - } - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} - -module.exports = { - symlinkType, - symlinkTypeSync -} - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const jsonFile = __webpack_require__(131) - -jsonFile.outputJson = u(__webpack_require__(133)) -jsonFile.outputJsonSync = __webpack_require__(134) -// aliases -jsonFile.outputJSON = jsonFile.outputJson -jsonFile.outputJSONSync = jsonFile.outputJsonSync -jsonFile.writeJSON = jsonFile.writeJson -jsonFile.writeJSONSync = jsonFile.writeJsonSync -jsonFile.readJSON = jsonFile.readJson -jsonFile.readJSONSync = jsonFile.readJsonSync - -module.exports = jsonFile - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const jsonFile = __webpack_require__(132) - -module.exports = { - // jsonfile exports - readJson: u(jsonFile.readFile), - readJsonSync: jsonFile.readFileSync, - writeJson: u(jsonFile.writeFile), - writeJsonSync: jsonFile.writeFileSync -} - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - -var _fs -try { - _fs = __webpack_require__(102) -} catch (_) { - _fs = __webpack_require__(66) -} - -function readFile (file, options, callback) { - if (callback == null) { - callback = options - options = {} - } - - if (typeof options === 'string') { - options = {encoding: options} - } - - options = options || {} - var fs = options.fs || _fs - - var shouldThrow = true - if ('throws' in options) { - shouldThrow = options.throws - } - - fs.readFile(file, options, function (err, data) { - if (err) return callback(err) - - data = stripBom(data) - - var obj - try { - obj = JSON.parse(data, options ? options.reviver : null) - } catch (err2) { - if (shouldThrow) { - err2.message = file + ': ' + err2.message - return callback(err2) - } else { - return callback(null, null) - } - } - - callback(null, obj) - }) -} - -function readFileSync (file, options) { - options = options || {} - if (typeof options === 'string') { - options = {encoding: options} - } - - var fs = options.fs || _fs - - var shouldThrow = true - if ('throws' in options) { - shouldThrow = options.throws - } - - try { - var content = fs.readFileSync(file, options) - content = stripBom(content) - return JSON.parse(content, options.reviver) - } catch (err) { - if (shouldThrow) { - err.message = file + ': ' + err.message - throw err - } else { - return null - } - } -} - -function stringify (obj, options) { - var spaces - var EOL = '\n' - if (typeof options === 'object' && options !== null) { - if (options.spaces) { - spaces = options.spaces - } - if (options.EOL) { - EOL = options.EOL - } - } - - var str = JSON.stringify(obj, options ? options.replacer : null, spaces) - - return str.replace(/\n/g, EOL) + EOL -} - -function writeFile (file, obj, options, callback) { - if (callback == null) { - callback = options - options = {} - } - options = options || {} - var fs = options.fs || _fs - - var str = '' - try { - str = stringify(obj, options) - } catch (err) { - // Need to return whether a callback was passed or not - if (callback) callback(err, null) - return - } - - fs.writeFile(file, str, options, callback) -} - -function writeFileSync (file, obj, options) { - options = options || {} - var fs = options.fs || _fs - - var str = stringify(obj, options) - // not sure if fs.writeFileSync returns anything, but just in case - return fs.writeFileSync(file, str, options) -} - -function stripBom (content) { - // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified - if (Buffer.isBuffer(content)) content = content.toString('utf8') - content = content.replace(/^\uFEFF/, '') - return content -} - -var jsonfile = { - readFile: readFile, - readFileSync: readFileSync, - writeFile: writeFile, - writeFileSync: writeFileSync -} - -module.exports = jsonfile - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const path = __webpack_require__(82) -const mkdir = __webpack_require__(111) -const pathExists = __webpack_require__(120).pathExists -const jsonFile = __webpack_require__(131) - -function outputJson (file, data, options, callback) { - if (typeof options === 'function') { - callback = options - options = {} - } - - const dir = path.dirname(file) - - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return jsonFile.writeJson(file, data, options, callback) - - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - jsonFile.writeJson(file, data, options, callback) - }) - }) -} - -module.exports = outputJson - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const mkdir = __webpack_require__(111) -const jsonFile = __webpack_require__(131) - -function outputJsonSync (file, data, options) { - const dir = path.dirname(file) - - if (!fs.existsSync(dir)) { - mkdir.mkdirsSync(dir) - } - - jsonFile.writeJsonSync(file, data, options) -} - -module.exports = outputJsonSync - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = { - moveSync: __webpack_require__(136) -} - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const copySync = __webpack_require__(109).copySync -const removeSync = __webpack_require__(122).removeSync -const mkdirpSync = __webpack_require__(111).mkdirpSync -const stat = __webpack_require__(116) - -function moveSync (src, dest, opts) { - opts = opts || {} - const overwrite = opts.overwrite || opts.clobber || false - - const { srcStat } = stat.checkPathsSync(src, dest, 'move') - stat.checkParentPathsSync(src, srcStat, dest, 'move') - mkdirpSync(path.dirname(dest)) - return doRename(src, dest, overwrite) -} - -function doRename (src, dest, overwrite) { - if (overwrite) { - removeSync(dest) - return rename(src, dest, overwrite) - } - if (fs.existsSync(dest)) throw new Error('dest already exists.') - return rename(src, dest, overwrite) -} - -function rename (src, dest, overwrite) { - try { - fs.renameSync(src, dest) - } catch (err) { - if (err.code !== 'EXDEV') throw err - return moveAcrossDevice(src, dest, overwrite) - } -} - -function moveAcrossDevice (src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - } - copySync(src, dest, opts) - return removeSync(src) -} - -module.exports = moveSync - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -module.exports = { - move: u(__webpack_require__(138)) -} - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const copy = __webpack_require__(118).copy -const remove = __webpack_require__(122).remove -const mkdirp = __webpack_require__(111).mkdirp -const pathExists = __webpack_require__(120).pathExists -const stat = __webpack_require__(116) - -function move (src, dest, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - - const overwrite = opts.overwrite || opts.clobber || false - - stat.checkPaths(src, dest, 'move', (err, stats) => { - if (err) return cb(err) - const { srcStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'move', err => { - if (err) return cb(err) - mkdirp(path.dirname(dest), err => { - if (err) return cb(err) - return doRename(src, dest, overwrite, cb) - }) - }) - }) -} - -function doRename (src, dest, overwrite, cb) { - if (overwrite) { - return remove(dest, err => { - if (err) return cb(err) - return rename(src, dest, overwrite, cb) - }) - } - pathExists(dest, (err, destExists) => { - if (err) return cb(err) - if (destExists) return cb(new Error('dest already exists.')) - return rename(src, dest, overwrite, cb) - }) -} - -function rename (src, dest, overwrite, cb) { - fs.rename(src, dest, err => { - if (!err) return cb() - if (err.code !== 'EXDEV') return cb(err) - return moveAcrossDevice(src, dest, overwrite, cb) - }) -} - -function moveAcrossDevice (src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - } - copy(src, dest, opts, err => { - if (err) return cb(err) - return remove(src, cb) - }) -} - -module.exports = move - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const u = __webpack_require__(101).fromCallback -const fs = __webpack_require__(102) -const path = __webpack_require__(82) -const mkdir = __webpack_require__(111) -const pathExists = __webpack_require__(120).pathExists - -function outputFile (file, data, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding - encoding = 'utf8' - } - - const dir = path.dirname(file) - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return fs.writeFile(file, data, encoding, callback) - - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - - fs.writeFile(file, data, encoding, callback) - }) - }) -} - -function outputFileSync (file, ...args) { - const dir = path.dirname(file) - if (fs.existsSync(dir)) { - return fs.writeFileSync(file, ...args) - } - mkdir.mkdirsSync(dir) - fs.writeFileSync(file, ...args) -} - -module.exports = { - outputFile: u(outputFile), - outputFileSync -} - - -/***/ }), -/* 140 */ -/***/ (function(module, exports) { - -// allows us to inject a mock date in tests -module.exports = () => new Date(); - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -function padWithZeros(vNumber, width) { - var numAsString = vNumber.toString(); - while (numAsString.length < width) { - numAsString = "0" + numAsString; - } - return numAsString; -} - -function addZero(vNumber) { - return padWithZeros(vNumber, 2); -} - -/** - * Formats the TimeOffset - * Thanks to http://www.svendtofte.com/code/date_format/ - * @private - */ -function offset(timezoneOffset) { - var os = Math.abs(timezoneOffset); - var h = String(Math.floor(os / 60)); - var m = String(os % 60); - if (h.length === 1) { - h = "0" + h; - } - if (m.length === 1) { - m = "0" + m; - } - return timezoneOffset < 0 ? "+" + h + m : "-" + h + m; -} - -function datePart(date, displayUTC, part) { - return displayUTC ? date["getUTC" + part]() : date["get" + part](); -} - -function asString(format, date) { - if (typeof format !== "string") { - date = format; - format = module.exports.ISO8601_FORMAT; - } - if (!date) { - date = module.exports.now(); - } - - var displayUTC = format.indexOf("O") > -1; - - var vDay = addZero(datePart(date, displayUTC, "Date")); - var vMonth = addZero(datePart(date, displayUTC, "Month") + 1); - var vYearLong = addZero(datePart(date, displayUTC, "FullYear")); - var vYearShort = addZero(vYearLong.substring(2, 4)); - var vYear = format.indexOf("yyyy") > -1 ? vYearLong : vYearShort; - var vHour = addZero(datePart(date, displayUTC, "Hours")); - var vMinute = addZero(datePart(date, displayUTC, "Minutes")); - var vSecond = addZero(datePart(date, displayUTC, "Seconds")); - var vMillisecond = padWithZeros( - datePart(date, displayUTC, "Milliseconds"), - 3 - ); - var vTimeZone = offset(date.getTimezoneOffset()); - var formatted = format - .replace(/dd/g, vDay) - .replace(/MM/g, vMonth) - .replace(/y{1,4}/g, vYear) - .replace(/hh/g, vHour) - .replace(/mm/g, vMinute) - .replace(/ss/g, vSecond) - .replace(/SSS/g, vMillisecond) - .replace(/O/g, vTimeZone); - return formatted; -} - -function extractDateParts(pattern, str, missingValuesDate) { - var matchers = [ - { - pattern: /y{1,4}/, - regexp: "\\d{1,4}", - fn: function(date, value) { - date.setFullYear(value); - } - }, - { - pattern: /MM/, - regexp: "\\d{1,2}", - fn: function(date, value) { - date.setMonth(value - 1); - } - }, - { - pattern: /dd/, - regexp: "\\d{1,2}", - fn: function(date, value) { - date.setDate(value); - } - }, - { - pattern: /hh/, - regexp: "\\d{1,2}", - fn: function(date, value) { - date.setHours(value); - } - }, - { - pattern: /mm/, - regexp: "\\d\\d", - fn: function(date, value) { - date.setMinutes(value); - } - }, - { - pattern: /ss/, - regexp: "\\d\\d", - fn: function(date, value) { - date.setSeconds(value); - } - }, - { - pattern: /SSS/, - regexp: "\\d\\d\\d", - fn: function(date, value) { - date.setMilliseconds(value); - } - }, - { - pattern: /O/, - regexp: "[+-]\\d{3,4}|Z", - fn: function(date, value) { - if (value === "Z") { - value = 0; - } - var offset = Math.abs(value); - var minutes = (offset % 100) + Math.floor(offset / 100) * 60; - date.setMinutes(date.getMinutes() + (value > 0 ? minutes : -minutes)); - } - } - ]; - - var parsedPattern = matchers.reduce( - function(p, m) { - if (m.pattern.test(p.regexp)) { - m.index = p.regexp.match(m.pattern).index; - p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")"); - } else { - m.index = -1; - } - return p; - }, - { regexp: pattern, index: [] } - ); - - var dateFns = matchers.filter(function(m) { - return m.index > -1; - }); - dateFns.sort(function(a, b) { - return a.index - b.index; - }); - - var matcher = new RegExp(parsedPattern.regexp); - var matches = matcher.exec(str); - if (matches) { - var date = missingValuesDate || module.exports.now(); - dateFns.forEach(function(f, i) { - f.fn(date, matches[i + 1]); - }); - return date; - } - - throw new Error( - "String '" + str + "' could not be parsed as '" + pattern + "'" - ); -} - -function parse(pattern, str, missingValuesDate) { - if (!pattern) { - throw new Error("pattern must be supplied"); - } - - return extractDateParts(pattern, str, missingValuesDate); -} - -/** - * Used for testing - replace this function with a fixed date. - */ -function now() { - return new Date(); -} - -module.exports = asString; -module.exports.asString = asString; -module.exports.parse = parse; -module.exports.now = now; -module.exports.ISO8601_FORMAT = "yyyy-MM-ddThh:mm:ss.SSS"; -module.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ss.SSSO"; -module.exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS"; -module.exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS"; - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)("streamroller:fileNameFormatter"); -const path = __webpack_require__(82); -const FILENAME_SEP = "."; -const ZIP_EXT = ".gz"; - -module.exports = ({ - file, - keepFileExt, - needsIndex, - alwaysIncludeDate, - compress -}) => { - const dirAndName = path.join(file.dir, file.name); - - const ext = f => f + file.ext; - - const index = (f, i, d) => - (needsIndex || !d) && i ? f + FILENAME_SEP + i : f; - - const date = (f, i, d) => { - return (i > 0 || alwaysIncludeDate) && d ? f + FILENAME_SEP + d : f; - }; - - const gzip = (f, i) => (i && compress ? f + ZIP_EXT : f); - - const parts = keepFileExt - ? [date, index, ext, gzip] - : [ext, date, index, gzip]; - - return ({ date, index }) => { - debug(`_formatFileName: date=${date}, index=${index}`); - return parts.reduce( - (filename, part) => part(filename, index, date), - dirAndName - ); - }; -}; - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)("streamroller:fileNameParser"); -const FILENAME_SEP = "."; -const ZIP_EXT = ".gz"; -const format = __webpack_require__(141); - -module.exports = ({ file, keepFileExt, pattern }) => { - // All these functions take two arguments: f, the filename, and p, the result placeholder - // They return the filename with any matching parts removed. - // The "zip" function, for instance, removes the ".gz" part of the filename (if present) - const zip = (f, p) => { - if (f.endsWith(ZIP_EXT)) { - debug("it is gzipped"); - p.isCompressed = true; - return f.slice(0, -1 * ZIP_EXT.length); - } - return f; - }; - - const __NOT_MATCHING__ = "__NOT_MATCHING__"; - - const extAtEnd = f => { - if (f.startsWith(file.name) && f.endsWith(file.ext)) { - debug("it starts and ends with the right things"); - return f.slice(file.name.length + 1, -1 * file.ext.length); - } - return __NOT_MATCHING__; - }; - - const extInMiddle = f => { - if (f.startsWith(file.base)) { - debug("it starts with the right things"); - return f.slice(file.base.length + 1); - } - return __NOT_MATCHING__; - }; - - const dateAndIndex = (f, p) => { - const items = f.split(FILENAME_SEP); - let indexStr = items[items.length - 1]; - debug("items: ", items, ", indexStr: ", indexStr); - let dateStr = f; - if (indexStr !== undefined && indexStr.match(/^\d+$/)) { - dateStr = f.slice(0, -1 * (indexStr.length + 1)); - debug(`dateStr is ${dateStr}`); - if (pattern && !dateStr) { - dateStr = indexStr; - indexStr = "0"; - } - } else { - indexStr = "0"; - } - - try { - // Two arguments for new Date() are intentional. This will set other date - // components to minimal values in the current timezone instead of UTC, - // as new Date(0) will do. - const date = format.parse(pattern, dateStr, new Date(0, 0)); - if (format.asString(pattern, date) !== dateStr) return f; - p.index = parseInt(indexStr, 10); - p.date = dateStr; - p.timestamp = date.getTime(); - return ""; - } catch (e) { - //not a valid date, don't panic. - debug(`Problem parsing ${dateStr} as ${pattern}, error was: `, e); - return f; - } - }; - - const index = (f, p) => { - if (f.match(/^\d+$/)) { - debug("it has an index"); - p.index = parseInt(f, 10); - return ""; - } - return f; - }; - - let parts = [ - zip, - keepFileExt ? extAtEnd : extInMiddle, - pattern ? dateAndIndex : index - ]; - - return filename => { - let result = { filename, index: 0, isCompressed: false }; - // pass the filename through each of the file part parsers - let whatsLeftOver = parts.reduce( - (remains, part) => part(remains, result), - filename - ); - // if there's anything left after parsing, then it wasn't a valid filename - return whatsLeftOver ? null : result; - }; -}; - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)('streamroller:moveAndMaybeCompressFile'); -const fs = __webpack_require__(99); -const zlib = __webpack_require__(145); - -const moveAndMaybeCompressFile = async ( - sourceFilePath, - targetFilePath, - needCompress -) => { - if (sourceFilePath === targetFilePath) { - debug( - `moveAndMaybeCompressFile: source and target are the same, not doing anything` - ); - return; - } - if (await fs.pathExists(sourceFilePath)) { - - debug( - `moveAndMaybeCompressFile: moving file from ${sourceFilePath} to ${targetFilePath} ${ - needCompress ? "with" : "without" - } compress` - ); - if (needCompress) { - await new Promise((resolve, reject) => { - fs.createReadStream(sourceFilePath) - .pipe(zlib.createGzip()) - .pipe(fs.createWriteStream(targetFilePath)) - .on("finish", () => { - debug( - `moveAndMaybeCompressFile: finished compressing ${targetFilePath}, deleting ${sourceFilePath}` - ); - fs.unlink(sourceFilePath) - .then(resolve) - .catch(() => { - debug(`Deleting ${sourceFilePath} failed, truncating instead`); - fs.truncate(sourceFilePath).then(resolve).catch(reject) - }); - }); - }); - } else { - debug( - `moveAndMaybeCompressFile: deleting file=${targetFilePath}, renaming ${sourceFilePath} to ${targetFilePath}` - ); - try { - await fs.move(sourceFilePath, targetFilePath, { overwrite: true }); - } catch (e) { - debug( - `moveAndMaybeCompressFile: error moving ${sourceFilePath} to ${targetFilePath}`, e - ); - debug(`Trying copy+truncate instead`); - await fs.copy(sourceFilePath, targetFilePath, { overwrite: true }); - await fs.truncate(sourceFilePath); - } - } - } -}; - -module.exports = moveAndMaybeCompressFile; - - -/***/ }), -/* 145 */ -/***/ (function(module, exports) { - -module.exports = require("zlib"); - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - -const RollingFileWriteStream = __webpack_require__(98); - -// just to adapt the previous version -class RollingFileStream extends RollingFileWriteStream { - constructor(filename, size, backups, options) { - if (!options) { - options = {}; - } - if (size) { - options.maxSize = size; - } - if (!backups) { - backups = 1; - } - options.numToKeep = backups; - super(filename, options); - this.backups = this.options.numToKeep; - this.size = this.options.maxSize; - } - - get theStream() { - return this.currentFileStream; - } - -} - -module.exports = RollingFileStream; - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - -const RollingFileWriteStream = __webpack_require__(98); - -// just to adapt the previous version -class DateRollingFileStream extends RollingFileWriteStream { - constructor(filename, pattern, options) { - if (pattern && typeof(pattern) === 'object') { - options = pattern; - pattern = null; - } - if (!options) { - options = {}; - } - if (!pattern) { - pattern = 'yyyy-MM-dd'; - } - if (options.daysToKeep) { - options.numToKeep = options.daysToKeep; - } - if (pattern.startsWith('.')) { - pattern = pattern.substring(1); - } - options.pattern = pattern; - super(filename, options); - this.mode = this.options.mode; - } - - get theStream() { - return this.currentFileStream; - } - -} - -module.exports = DateRollingFileStream; - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - -const streams = __webpack_require__(97); -const os = __webpack_require__(76); - -const eol = os.EOL; - -/** - * File appender that rolls files according to a date pattern. - * @filename base filename. - * @pattern the format that will be added to the end of filename when rolling, - * also used to check when to roll files - defaults to '.yyyy-MM-dd' - * @layout layout function for log messages - defaults to basicLayout - * @timezoneOffset optional timezone offset in minutes - defaults to system local - */ -function appender( - filename, - pattern, - layout, - options, - timezoneOffset -) { - // the options for file appender use maxLogSize, but the docs say any file appender - // options should work for dateFile as well. - options.maxSize = options.maxLogSize; - - const logFile = new streams.DateRollingFileStream( - filename, - pattern, - options - ); - - logFile.on("drain", () => { - process.emit("log4js:pause", false); - }); - - const app = function (logEvent) { - if (!logFile.write(layout(logEvent, timezoneOffset) + eol, "utf8")) { - process.emit("log4js:pause", true); - } - }; - - app.shutdown = function (complete) { - logFile.write('', 'utf-8', () => { - logFile.end(complete); - }); - }; - - return app; -} - -function configure(config, layouts) { - let layout = layouts.basicLayout; - - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - - if (!config.alwaysIncludePattern) { - config.alwaysIncludePattern = false; - } - - return appender( - config.filename, - config.pattern, - layout, - config, - config.timezoneOffset - ); -} - -module.exports.configure = configure; - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)('log4js:fileSync'); -const path = __webpack_require__(82); -const fs = __webpack_require__(66); -const os = __webpack_require__(76); - -const eol = os.EOL || '\n'; - -function touchFile(file, options) { - // if the file exists, nothing to do - if (fs.existsSync(file)) { - return; - } - - // touch the file to apply flags (like w to truncate the file) - const id = fs.openSync(file, options.flags, options.mode); - fs.closeSync(id); -} - -class RollingFileSync { - constructor(filename, size, backups, options) { - debug('In RollingFileStream'); - - function throwErrorIfArgumentsAreNotValid() { - if (!filename || !size || size <= 0) { - throw new Error('You must specify a filename and file size'); - } - } - - throwErrorIfArgumentsAreNotValid(); - - this.filename = filename; - this.size = size; - this.backups = backups || 1; - this.options = options; - this.currentSize = 0; - - function currentFileSize(file) { - let fileSize = 0; - - try { - fileSize = fs.statSync(file).size; - } catch (e) { - // file does not exist - touchFile(file, options); - } - return fileSize; - } - - this.currentSize = currentFileSize(this.filename); - } - - shouldRoll() { - debug('should roll with current size %d, and max size %d', this.currentSize, this.size); - return this.currentSize >= this.size; - } - - roll(filename) { - const that = this; - const nameMatcher = new RegExp(`^${path.basename(filename)}`); - - function justTheseFiles(item) { - return nameMatcher.test(item); - } - - function index(filename_) { - return parseInt(filename_.substring((`${path.basename(filename)}.`).length), 10) || 0; - } - - function byIndex(a, b) { - if (index(a) > index(b)) { - return 1; - } - if (index(a) < index(b)) { - return -1; - } - - return 0; - } - - function increaseFileIndex(fileToRename) { - const idx = index(fileToRename); - debug(`Index of ${fileToRename} is ${idx}`); - if (idx < that.backups) { - // on windows, you can get a EEXIST error if you rename a file to an existing file - // so, we'll try to delete the file we're renaming to first - try { - fs.unlinkSync(`${filename}.${idx + 1}`); - } catch (e) { - // ignore err: if we could not delete, it's most likely that it doesn't exist - } - - debug(`Renaming ${fileToRename} -> ${filename}.${idx + 1}`); - fs.renameSync(path.join(path.dirname(filename), fileToRename), `${filename}.${idx + 1}`); - } - } - - function renameTheFiles() { - // roll the backups (rename file.n to file.n+1, where n <= numBackups) - debug('Renaming the old files'); - - const files = fs.readdirSync(path.dirname(filename)); - files.filter(justTheseFiles).sort(byIndex).reverse().forEach(increaseFileIndex); - } - - debug('Rolling, rolling, rolling'); - renameTheFiles(); - } - - /* eslint no-unused-vars:0 */ - write(chunk, encoding) { - const that = this; - - - function writeTheChunk() { - debug('writing the chunk to the file'); - that.currentSize += chunk.length; - fs.appendFileSync(that.filename, chunk); - } - - debug('in write'); - - - if (this.shouldRoll()) { - this.currentSize = 0; - this.roll(this.filename); - } - - writeTheChunk(); - } -} - -/** - * File Appender writing the logs to a text file. Supports rolling of logs by size. - * - * @param file file log messages will be written to - * @param layout a function that takes a logevent and returns a string - * (defaults to basicLayout). - * @param logSize - the maximum size (in bytes) for a log file, - * if not provided then logs won't be rotated. - * @param numBackups - the number of log files to keep after logSize - * has been reached (default 5) - * @param timezoneOffset - optional timezone offset in minutes - * (default system local) - * @param options - passed as is to fs options - */ -function fileAppender(file, layout, logSize, numBackups, timezoneOffset, options) { - debug('fileSync appender created'); - file = path.normalize(file); - numBackups = numBackups === undefined ? 5 : numBackups; - // there has to be at least one backup if logSize has been specified - numBackups = numBackups === 0 ? 1 : numBackups; - - function openTheStream(filePath, fileSize, numFiles) { - let stream; - - if (fileSize) { - stream = new RollingFileSync( - filePath, - fileSize, - numFiles, - options - ); - } else { - stream = (((f) => { - // touch the file to apply flags (like w to truncate the file) - touchFile(f, options); - - return { - write(data) { - fs.appendFileSync(f, data); - } - }; - }))(filePath); - } - - return stream; - } - - const logFile = openTheStream(file, logSize, numBackups); - - return (loggingEvent) => { - logFile.write(layout(loggingEvent, timezoneOffset) + eol); - }; -} - -function configure(config, layouts) { - let layout = layouts.basicLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - - const options = { - flags: config.flags || 'a', - encoding: config.encoding || 'utf8', - mode: config.mode || 0o644 - }; - - return fileAppender( - config.filename, - layout, - config.maxLogSize, - config.backups, - config.timezoneOffset, - options - ); -} - -module.exports.configure = configure; - - -/***/ }), -/* 150 */ -/***/ (function(module, exports) { - -function webpackEmptyContext(req) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; -} -webpackEmptyContext.keys = function() { return []; }; -webpackEmptyContext.resolve = webpackEmptyContext; -module.exports = webpackEmptyContext; -webpackEmptyContext.id = 150; - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - -const debug = __webpack_require__(68)('log4js:categories'); -const configuration = __webpack_require__(79); -const levels = __webpack_require__(83); -const appenders = __webpack_require__(84); - -const categories = new Map(); - -/** - * Add inherited config to this category. That includes extra appenders from parent, - * and level, if none is set on this category. - * This is recursive, so each parent also gets loaded with inherited appenders. - * Inheritance is blocked if a category has inherit=false - * @param {*} config - * @param {*} category the child category - * @param {string} categoryName dotted path to category - * @return {void} - */ -function inheritFromParent(config, category, categoryName) { - if (category.inherit === false) return; - const lastDotIndex = categoryName.lastIndexOf('.'); - if (lastDotIndex < 0) return; // category is not a child - const parentCategoryName = categoryName.substring(0, lastDotIndex); - let parentCategory = config.categories[parentCategoryName]; - - - if (!parentCategory) { - // parent is missing, so implicitly create it, so that it can inherit from its parents - parentCategory = { inherit: true, appenders: [] }; - } - - // make sure parent has had its inheritance taken care of before pulling its properties to this child - inheritFromParent(config, parentCategory, parentCategoryName); - - // if the parent is not in the config (because we just created it above), - // and it inherited a valid configuration, add it to config.categories - if (!config.categories[parentCategoryName] - && parentCategory.appenders - && parentCategory.appenders.length - && parentCategory.level) { - config.categories[parentCategoryName] = parentCategory; - } - - category.appenders = category.appenders || []; - category.level = category.level || parentCategory.level; - - // merge in appenders from parent (parent is already holding its inherited appenders) - parentCategory.appenders.forEach((ap) => { - if (!category.appenders.includes(ap)) { - category.appenders.push(ap); - } - }); - category.parent = parentCategory; -} - - -/** - * Walk all categories in the config, and pull down any configuration from parent to child. - * This includes inherited appenders, and level, where level is not set. - * Inheritance is skipped where a category has inherit=false. - * @param {*} config - */ -function addCategoryInheritance(config) { - if (!config.categories) return; - const categoryNames = Object.keys(config.categories); - categoryNames.forEach((name) => { - const category = config.categories[name]; - // add inherited appenders and level to this category - inheritFromParent(config, category, name); - }); -} - -configuration.addPreProcessingListener(config => addCategoryInheritance(config)); - -configuration.addListener((config) => { - configuration.throwExceptionIf( - config, - configuration.not(configuration.anObject(config.categories)), - 'must have a property "categories" of type object.' - ); - - const categoryNames = Object.keys(config.categories); - configuration.throwExceptionIf( - config, - configuration.not(categoryNames.length), - 'must define at least one category.' - ); - - categoryNames.forEach((name) => { - const category = config.categories[name]; - configuration.throwExceptionIf( - config, - [ - configuration.not(category.appenders), - configuration.not(category.level) - ], - `category "${name}" is not valid (must be an object with properties "appenders" and "level")` - ); - - configuration.throwExceptionIf( - config, - configuration.not(Array.isArray(category.appenders)), - `category "${name}" is not valid (appenders must be an array of appender names)` - ); - - configuration.throwExceptionIf( - config, - configuration.not(category.appenders.length), - `category "${name}" is not valid (appenders must contain at least one appender name)` - ); - - if (Object.prototype.hasOwnProperty.call(category, 'enableCallStack')) { - configuration.throwExceptionIf( - config, - typeof category.enableCallStack !== 'boolean', - `category "${name}" is not valid (enableCallStack must be boolean type)` - ); - } - - category.appenders.forEach((appender) => { - configuration.throwExceptionIf( - config, - configuration.not(appenders.get(appender)), - `category "${name}" is not valid (appender "${appender}" is not defined)` - ); - }); - - configuration.throwExceptionIf( - config, - configuration.not(levels.getLevel(category.level)), - `category "${name}" is not valid (level "${category.level}" not recognised;` - + ` valid levels are ${levels.levels.join(', ')})` - ); - }); - - configuration.throwExceptionIf( - config, - configuration.not(config.categories.default), - 'must define a "default" category.' - ); -}); - -const setup = (config) => { - categories.clear(); - - const categoryNames = Object.keys(config.categories); - categoryNames.forEach((name) => { - const category = config.categories[name]; - const categoryAppenders = []; - category.appenders.forEach((appender) => { - categoryAppenders.push(appenders.get(appender)); - debug(`Creating category ${name}`); - categories.set( - name, - { - appenders: categoryAppenders, - level: levels.getLevel(category.level), - enableCallStack: category.enableCallStack || false - } - ); - }); - }); -}; - -setup({ categories: { default: { appenders: ['out'], level: 'OFF' } } }); -configuration.addListener(setup); - -const configForCategory = (category) => { - debug(`configForCategory: searching for config for ${category}`); - if (categories.has(category)) { - debug(`configForCategory: ${category} exists in config, returning it`); - return categories.get(category); - } - if (category.indexOf('.') > 0) { - debug(`configForCategory: ${category} has hierarchy, searching for parents`); - return configForCategory(category.substring(0, category.lastIndexOf('.'))); - } - debug('configForCategory: returning config for default category'); - return configForCategory('default'); -}; - -const appendersForCategory = category => configForCategory(category).appenders; -const getLevelForCategory = category => configForCategory(category).level; - -const setLevelForCategory = (category, level) => { - let categoryConfig = categories.get(category); - debug(`setLevelForCategory: found ${categoryConfig} for ${category}`); - if (!categoryConfig) { - const sourceCategoryConfig = configForCategory(category); - debug('setLevelForCategory: no config found for category, ' - + `found ${sourceCategoryConfig} for parents of ${category}`); - categoryConfig = { appenders: sourceCategoryConfig.appenders }; - } - categoryConfig.level = level; - categories.set(category, categoryConfig); -}; - -const getEnableCallStackForCategory = category => configForCategory(category).enableCallStack === true; -const setEnableCallStackForCategory = (category, useCallStack) => { - configForCategory(category).enableCallStack = useCallStack; -}; - -module.exports = { - appendersForCategory, - getLevelForCategory, - setLevelForCategory, - getEnableCallStackForCategory, - setEnableCallStackForCategory, -}; - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint no-underscore-dangle:0 */ -const debug = __webpack_require__(68)("log4js:logger"); -const LoggingEvent = __webpack_require__(86); -const levels = __webpack_require__(83); -const clustering = __webpack_require__(85); -const categories = __webpack_require__(151); -const configuration = __webpack_require__(79); - -const stackReg = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/; -function defaultParseCallStack(data, skipIdx = 4) { - const stacklines = data.stack.split("\n").slice(skipIdx); - const lineMatch = stackReg.exec(stacklines[0]); - if (lineMatch && lineMatch.length === 6) { - return { - functionName: lineMatch[1], - fileName: lineMatch[2], - lineNumber: parseInt(lineMatch[3], 10), - columnNumber: parseInt(lineMatch[4], 10), - callStack: stacklines.join("\n") - }; - } - return null; -} - -/** - * Logger to log messages. - * use {@see log4js#getLogger(String)} to get an instance. - * - * @name Logger - * @namespace Log4js - * @param name name of category to log to - * @param level - the loglevel for the category - * @param dispatch - the function which will receive the logevents - * - * @author Stephan Strittmatter - */ -class Logger { - constructor(name) { - if (!name) { - throw new Error("No category provided."); - } - this.category = name; - this.context = {}; - this.parseCallStack = defaultParseCallStack; - debug(`Logger created (${this.category}, ${this.level})`); - } - - get level() { - return levels.getLevel( - categories.getLevelForCategory(this.category), - levels.TRACE - ); - } - - set level(level) { - categories.setLevelForCategory( - this.category, - levels.getLevel(level, this.level) - ); - } - - get useCallStack() { - return categories.getEnableCallStackForCategory(this.category); - } - - set useCallStack(bool) { - categories.setEnableCallStackForCategory(this.category, bool === true); - } - - log(level, ...args) { - const logLevel = levels.getLevel(level, levels.INFO); - if (this.isLevelEnabled(logLevel)) { - this._log(logLevel, args); - } - } - - isLevelEnabled(otherLevel) { - return this.level.isLessThanOrEqualTo(otherLevel); - } - - _log(level, data) { - debug(`sending log data (${level}) to appenders`); - const loggingEvent = new LoggingEvent( - this.category, - level, - data, - this.context, - this.useCallStack && this.parseCallStack(new Error()) - ); - clustering.send(loggingEvent); - } - - addContext(key, value) { - this.context[key] = value; - } - - removeContext(key) { - delete this.context[key]; - } - - clearContext() { - this.context = {}; - } - - setParseCallStackFunction(parseFunction) { - this.parseCallStack = parseFunction; - } -} - -function addLevelMethods(target) { - const level = levels.getLevel(target); - - const levelStrLower = level.toString().toLowerCase(); - const levelMethod = levelStrLower.replace(/_([a-z])/g, g => - g[1].toUpperCase() - ); - const isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1); - - Logger.prototype[`is${isLevelMethod}Enabled`] = function() { - return this.isLevelEnabled(level); - }; - - Logger.prototype[levelMethod] = function(...args) { - this.log(level, ...args); - }; -} - -levels.levels.forEach(addLevelMethods); - -configuration.addListener(() => { - levels.levels.forEach(addLevelMethods); -}); - -module.exports = Logger; - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-disable no-plusplus */ - -const levels = __webpack_require__(83); - -const DEFAULT_FORMAT = - ":remote-addr - -" + - ' ":method :url HTTP/:http-version"' + - ' :status :content-length ":referrer"' + - ' ":user-agent"'; - -/** - * Return request url path, - * adding this function prevents the Cyclomatic Complexity, - * for the assemble_tokens function at low, to pass the tests. - * - * @param {IncomingMessage} req - * @return {string} - * @api private - */ -function getUrl(req) { - return req.originalUrl || req.url; -} - -/** - * Adds custom {token, replacement} objects to defaults, - * overwriting the defaults if any tokens clash - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @param {Array} customTokens - * [{ token: string-or-regexp, replacement: string-or-replace-function }] - * @return {Array} - */ -function assembleTokens(req, res, customTokens) { - const arrayUniqueTokens = array => { - const a = array.concat(); - for (let i = 0; i < a.length; ++i) { - for (let j = i + 1; j < a.length; ++j) { - // not === because token can be regexp object - /* eslint eqeqeq:0 */ - if (a[i].token == a[j].token) { - a.splice(j--, 1); - } - } - } - return a; - }; - - const defaultTokens = []; - defaultTokens.push({ token: ":url", replacement: getUrl(req) }); - defaultTokens.push({ token: ":protocol", replacement: req.protocol }); - defaultTokens.push({ token: ":hostname", replacement: req.hostname }); - defaultTokens.push({ token: ":method", replacement: req.method }); - defaultTokens.push({ - token: ":status", - replacement: res.__statusCode || res.statusCode - }); - defaultTokens.push({ - token: ":response-time", - replacement: res.responseTime - }); - defaultTokens.push({ token: ":date", replacement: new Date().toUTCString() }); - defaultTokens.push({ - token: ":referrer", - replacement: req.headers.referer || req.headers.referrer || "" - }); - defaultTokens.push({ - token: ":http-version", - replacement: `${req.httpVersionMajor}.${req.httpVersionMinor}` - }); - defaultTokens.push({ - token: ":remote-addr", - replacement: - req.headers["x-forwarded-for"] || - req.ip || - req._remoteAddress || - (req.socket && - (req.socket.remoteAddress || - (req.socket.socket && req.socket.socket.remoteAddress))) - }); - defaultTokens.push({ - token: ":user-agent", - replacement: req.headers["user-agent"] - }); - defaultTokens.push({ - token: ":content-length", - replacement: - res.getHeader("content-length") || - (res.__headers && res.__headers["Content-Length"]) || - "-" - }); - defaultTokens.push({ - token: /:req\[([^\]]+)]/g, - replacement(_, field) { - return req.headers[field.toLowerCase()]; - } - }); - defaultTokens.push({ - token: /:res\[([^\]]+)]/g, - replacement(_, field) { - return ( - res.getHeader(field.toLowerCase()) || - (res.__headers && res.__headers[field]) - ); - } - }); - - return arrayUniqueTokens(customTokens.concat(defaultTokens)); -} - -/** - * Return formatted log line. - * - * @param {string} str - * @param {Array} tokens - * @return {string} - * @api private - */ -function format(str, tokens) { - for (let i = 0; i < tokens.length; i++) { - str = str.replace(tokens[i].token, tokens[i].replacement); - } - return str; -} - -/** - * Return RegExp Object about nolog - * - * @param {(string|Array)} nolog - * @return {RegExp} - * @api private - * - * syntax - * 1. String - * 1.1 "\\.gif" - * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga - * LOGGING http://example.com/hoge.agif - * 1.2 in "\\.gif|\\.jpg$" - * NOT LOGGING http://example.com/hoge.gif and - * http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga - * LOGGING http://example.com/hoge.agif, - * http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge - * 1.3 in "\\.(gif|jpe?g|png)$" - * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg - * LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3 - * 2. RegExp - * 2.1 in /\.(gif|jpe?g|png)$/ - * SAME AS 1.3 - * 3. Array - * 3.1 ["\\.jpg$", "\\.png", "\\.gif"] - * SAME AS "\\.jpg|\\.png|\\.gif" - */ -function createNoLogCondition(nolog) { - let regexp = null; - - if (nolog instanceof RegExp) { - regexp = nolog; - } - - if (typeof nolog === "string") { - regexp = new RegExp(nolog); - } - - if (Array.isArray(nolog)) { - // convert to strings - const regexpsAsStrings = nolog.map(reg => (reg.source ? reg.source : reg)); - regexp = new RegExp(regexpsAsStrings.join("|")); - } - - return regexp; -} - -/** - * Allows users to define rules around status codes to assign them to a specific - * logging level. - * There are two types of rules: - * - RANGE: matches a code within a certain range - * E.g. { 'from': 200, 'to': 299, 'level': 'info' } - * - CONTAINS: matches a code to a set of expected codes - * E.g. { 'codes': [200, 203], 'level': 'debug' } - * Note*: Rules are respected only in order of prescendence. - * - * @param {Number} statusCode - * @param {Level} currentLevel - * @param {Object} ruleSet - * @return {Level} - * @api private - */ -function matchRules(statusCode, currentLevel, ruleSet) { - let level = currentLevel; - - if (ruleSet) { - const matchedRule = ruleSet.find(rule => { - let ruleMatched = false; - if (rule.from && rule.to) { - ruleMatched = statusCode >= rule.from && statusCode <= rule.to; - } else { - ruleMatched = rule.codes.indexOf(statusCode) !== -1; - } - return ruleMatched; - }); - if (matchedRule) { - level = levels.getLevel(matchedRule.level, level); - } - } - return level; -} - -/** - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `level` A log4js levels instance. Supports also 'auto' - * - `nolog` A string or RegExp to exclude target logs - * - `statusRules` A array of rules for setting specific logging levels base on status codes - * - `context` Whether to add a response of express to the context - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * @return {Function} - * @param logger4js - * @param options - * @api public - */ -module.exports = function getLogger(logger4js, options) { - /* eslint no-underscore-dangle:0 */ - if (typeof options === "string" || typeof options === "function") { - options = { format: options }; - } else { - options = options || {}; - } - - const thisLogger = logger4js; - let level = levels.getLevel(options.level, levels.INFO); - const fmt = options.format || DEFAULT_FORMAT; - const nolog = createNoLogCondition(options.nolog); - - return (req, res, next) => { - // mount safety - if (req._logging) return next(); - - // nologs - if (nolog && nolog.test(req.originalUrl)) return next(); - - if (thisLogger.isLevelEnabled(level) || options.level === "auto") { - const start = new Date(); - const { writeHead } = res; - - // flag as logging - req._logging = true; - - // proxy for statusCode. - res.writeHead = (code, headers) => { - res.writeHead = writeHead; - res.writeHead(code, headers); - - res.__statusCode = code; - res.__headers = headers || {}; - }; - - // hook on end request to emit the log entry of the HTTP request. - res.on("finish", () => { - res.responseTime = new Date() - start; - // status code response level handling - if (res.statusCode && options.level === "auto") { - level = levels.INFO; - if (res.statusCode >= 300) level = levels.WARN; - if (res.statusCode >= 400) level = levels.ERROR; - } - level = matchRules(res.statusCode, level, options.statusRules); - - const combinedTokens = assembleTokens(req, res, options.tokens || []); - - if (options.context) thisLogger.addContext("res", res); - if (typeof fmt === "function") { - const line = fmt(req, res, str => format(str, combinedTokens)); - if (line) thisLogger.log(level, line); - } else { - thisLogger.log(level, format(fmt, combinedTokens)); - } - if (options.context) thisLogger.removeContext("res"); - }); - } - - // ensure next gets always called - return next(); - }; -}; - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const neovim_1 = __webpack_require__(155); -const log4js_1 = tslib_1.__importDefault(__webpack_require__(67)); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const plugin_1 = tslib_1.__importDefault(__webpack_require__(251)); -const semver_1 = tslib_1.__importDefault(__webpack_require__(1)); -const is_1 = __webpack_require__(250); -__webpack_require__(500); -const vscode_uri_1 = __webpack_require__(243); -const logger = __webpack_require__(64)('attach'); -const isTest = global.hasOwnProperty('__TEST__'); -exports.default = (opts, requestApi = true) => { - const nvim = neovim_1.attach(opts, log4js_1.default.getLogger('node-client'), requestApi); - const timeout = process.env.COC_CHANNEL_TIMEOUT ? parseInt(process.env.COC_CHANNEL_TIMEOUT, 10) : 30; - if (!global.hasOwnProperty('__TEST__')) { - nvim.call('coc#util#path_replace_patterns').then(prefixes => { - if (is_1.objectLiteral(prefixes)) { - const old_uri = vscode_uri_1.URI.file; - vscode_uri_1.URI.file = (path) => { - path = path.replace(/\\/g, '/'); - Object.keys(prefixes).forEach(k => path = path.replace(new RegExp('^' + k), prefixes[k])); - return old_uri(path); - }; - } - }).logError(); - } - nvim.setVar('coc_process_pid', process.pid, true); - const plugin = new plugin_1.default(nvim); - let clientReady = false; - let initialized = false; - nvim.on('notification', async (method, args) => { - switch (method) { - case 'VimEnter': { - if (!initialized && clientReady) { - initialized = true; - await plugin.init(); - } - break; - } - case 'TaskExit': - case 'TaskStderr': - case 'TaskStdout': - case 'GlobalChange': - case 'PromptInsert': - case 'InputChar': - case 'MenuInput': - case 'OptionSet': - await events_1.default.fire(method, args); - break; - case 'CocAutocmd': - await events_1.default.fire(args[0], args.slice(1)); - break; - default: { - let exists = plugin.hasAction(method); - if (!exists) { - if (global.hasOwnProperty('__TEST__')) - return; - console.error(`action "${method}" not registered`); - return; - } - try { - if (!plugin.isReady) { - logger.warn(`Plugin not ready when received "${method}"`, args); - } - await plugin.ready; - await plugin.cocAction(method, ...args); - } - catch (e) { - console.error(`Error on notification "${method}": ${e.message || e.toString()}`); - logger.error(`Notification error:`, method, args, e); - } - } - } - }); - nvim.on('request', async (method, args, resp) => { - let timer = setTimeout(() => { - logger.error('Request cost more than 3s', method, args); - }, timeout * 3000); - try { - if (method == 'CocAutocmd') { - await events_1.default.fire(args[0], args.slice(1)); - resp.send(); - } - else { - if (!plugin.hasAction(method)) { - throw new Error(`action "${method}" not registered`); - } - if (!plugin.isReady) { - logger.warn(`Plugin not ready when received "${method}"`, args); - } - let res = await plugin.cocAction(method, ...args); - resp.send(res); - } - clearTimeout(timer); - } - catch (e) { - clearTimeout(timer); - resp.send(e.message || e.toString(), true); - logger.error(`Request error:`, method, args, e); - } - }); - nvim.channelId.then(async (channelId) => { - clientReady = true; - // Used for test client on vim side - if (isTest) - nvim.command(`let g:coc_node_channel_id = ${channelId}`, true); - let json = __webpack_require__(331); - let { major, minor, patch } = semver_1.default.parse(json.version); - nvim.setClientInfo('coc', { major, minor, patch }, 'remote', {}, {}); - let entered = await nvim.getVvar('vim_did_enter'); - if (entered && !initialized) { - initialized = true; - await plugin.init(); - } - }).catch(e => { - console.error(`Channel create error: ${e.message}`); - }); - return plugin; -}; -//# sourceMappingURL=attach.js.map - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Window = exports.Tabpage = exports.Buffer = exports.NeovimClient = exports.Neovim = exports.attach = void 0; -var attach_1 = __webpack_require__(156); -Object.defineProperty(exports, "attach", { enumerable: true, get: function () { return attach_1.attach; } }); -var index_1 = __webpack_require__(209); -Object.defineProperty(exports, "Neovim", { enumerable: true, get: function () { return index_1.Neovim; } }); -Object.defineProperty(exports, "NeovimClient", { enumerable: true, get: function () { return index_1.NeovimClient; } }); -Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return index_1.Buffer; } }); -Object.defineProperty(exports, "Tabpage", { enumerable: true, get: function () { return index_1.Tabpage; } }); -Object.defineProperty(exports, "Window", { enumerable: true, get: function () { return index_1.Window; } }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.attach = void 0; -const net_1 = __webpack_require__(157); -const client_1 = __webpack_require__(158); -function attach({ reader: _reader, writer: _writer, proc, socket, }, logger = null, requestApi = true) { - let writer; - let reader; - let neovim; - if (socket) { - const client = net_1.createConnection(socket); - writer = client; - reader = client; - client.once('close', () => { - neovim.detach(); - }); - } - else if (_reader && _writer) { - writer = _writer; - reader = _reader; - } - else if (proc) { - writer = proc.stdin; - reader = proc.stdout; - proc.once('disconnect', () => { - neovim.detach(); - }); - } - writer.on('error', err => { - if (err.code == 'EPIPE') { - neovim.detach(); - } - }); - if (writer && reader) { - neovim = new client_1.NeovimClient(logger); - neovim.attach({ - writer, - reader, - }, requestApi); - return neovim; - } - throw new Error('Invalid arguments, could not attach'); -} -exports.attach = attach; - - -/***/ }), -/* 157 */ -/***/ (function(module, exports) { - -module.exports = require("net"); - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NeovimClient = exports.AsyncResponse = void 0; -/** - * Handles attaching transport - */ -const nvim_1 = __webpack_require__(159); -const vim_1 = __webpack_require__(204); -const Neovim_1 = __webpack_require__(208); -const Buffer_1 = __webpack_require__(196); -const Window_1 = __webpack_require__(199); -const Tabpage_1 = __webpack_require__(201); -const logger_1 = __webpack_require__(203); -const logger = logger_1.createLogger('client'); -const isVim = process.env.VIM_NODE_RPC == '1'; -class AsyncResponse { - constructor(requestId, cb) { - this.requestId = requestId; - this.cb = cb; - this.finished = false; - } - finish(err, res) { - if (this.finished) - return; - this.finished = true; - if (err) { - this.cb(new Error(err)); - return; - } - this.cb(null, res); - } -} -exports.AsyncResponse = AsyncResponse; -class NeovimClient extends Neovim_1.Neovim { - constructor(logger) { - // Neovim has no `data` or `metadata` - super({}); - this.logger = logger; - this.requestId = 1; - this.responses = new Map(); - this.attachedBuffers = new Map(); - this.timers = new Map(); - Object.defineProperty(this, 'client', { - value: this - }); - let transport = isVim ? new vim_1.VimTransport(logger) : new nvim_1.NvimTransport(logger); - this.setTransport(transport); - this.transportAttached = false; - this.handleRequest = this.handleRequest.bind(this); - this.handleNotification = this.handleNotification.bind(this); - } - logError(msg, ...args) { - if (!this.logger) - return; - this.logger.error(msg, ...args); - } - createBuffer(id) { - return new Buffer_1.Buffer({ - transport: this.transport, - data: id, - client: this - }); - } - createWindow(id) { - return new Window_1.Window({ - transport: this.transport, - data: id, - client: this - }); - } - createTabpage(id) { - return new Tabpage_1.Tabpage({ - transport: this.transport, - data: id, - client: this - }); - } - send(arr) { - this.transport.send(arr); - } - /** Attaches msgpack to read/write streams * */ - attach({ reader, writer, }, requestApi = true) { - this.transport.attach(writer, reader, this); - this.transportAttached = true; - this.setupTransport(requestApi); - } - /* called when attach process disconnected*/ - detach() { - for (let timer of this.timers.values()) { - clearTimeout(timer); - } - this.transport.detach(); - this.transportAttached = false; - } - get isApiReady() { - return this.transportAttached && typeof this._channelId !== 'undefined'; - } - get channelId() { - return this._isReady.then(() => { - return this._channelId; - }); - } - isAttached(bufnr) { - return this.attachedBuffers.has(bufnr); - } - handleRequest(method, args, resp) { - this.emit('request', method, args, resp); - } - sendAsyncRequest(method, args) { - let id = this.requestId; - this.requestId = id + 1; - this.notify('nvim_call_function', ['coc#rpc#async_request', [id, method, args || []]]); - return new Promise((resolve, reject) => { - let response = new AsyncResponse(id, (err, res) => { - if (err) - return reject(err); - resolve(res); - }); - this.responses.set(id, response); - }); - } - emitNotification(method, args) { - if (method.endsWith('_event')) { - if (method.startsWith('nvim_buf_')) { - const shortName = method.replace(/nvim_buf_(.*)_event/, '$1'); - const { id } = args[0]; - if (!this.attachedBuffers.has(id)) - return; - const bufferMap = this.attachedBuffers.get(id); - const cbs = bufferMap.get(shortName) || []; - cbs.forEach(cb => cb(...args)); - // Handle `nvim_buf_detach_event` - // clean `attachedBuffers` since it will no longer be attached - if (shortName === 'detach') { - this.attachedBuffers.delete(id); - } - return; - } - // async_request_event from vim - if (method.startsWith('nvim_async_request')) { - const [id, method, arr] = args; - this.handleRequest(method, arr, { - send: (resp, isError) => { - this.notify('nvim_call_function', ['coc#rpc#async_response', [id, resp, isError]]); - } - }); - } - // nvim_async_response_event - if (method.startsWith('nvim_async_response')) { - const [id, err, res] = args; - const response = this.responses.get(id); - if (!response) { - // tslint:disable-next-line: no-console - console.error(`Response not found for request ${id}`); - return; - } - this.responses.delete(id); - response.finish(err, res); - return; - } - // tslint:disable-next-line: no-console - // console.error(`Unhandled event: ${method}`) - } - else { - this.emit('notification', method, args); - } - } - handleNotification(method, args) { - this.emitNotification(method, args); - } - // Listen and setup handlers for transport - setupTransport(requestApi = true) { - if (!this.transportAttached) { - throw new Error('Not attached to input/output'); - } - this.transport.on('request', this.handleRequest); - this.transport.on('notification', this.handleNotification); - this.transport.on('detach', () => { - this.emit('disconnect'); - this.transport.removeAllListeners('request'); - this.transport.removeAllListeners('notification'); - this.transport.removeAllListeners('detach'); - }); - if (requestApi) { - this._isReady = this.generateApi(); - } - else { - this._channelId = 0; - this._isReady = Promise.resolve(true); - } - } - requestApi() { - return new Promise((resolve, reject) => { - this.transport.request('nvim_get_api_info', [], (err, res) => { - if (err) { - reject(new Error(Array.isArray(err) ? err[1] : err.message || err.toString())); - } - else { - resolve(res); - } - }); - }); - } - async generateApi() { - let results; - try { - results = await this.requestApi(); - } - catch (err) { - // tslint:disable-next-line: no-console - console.error('Could not get vim api results'); - logger.error(err); - } - if (results) { - try { - const [channelId, metadata] = results; - this.functions = metadata.functions.map(f => f.name); - this._channelId = channelId; - return true; - } - catch (err) { - logger.error(err.stack); - return null; - } - } - return null; - } - attachBufferEvent(buffer, eventName, cb) { - const bufferMap = this.attachedBuffers.get(buffer.id) || new Map(); - const cbs = bufferMap.get(eventName) || []; - if (cbs.includes(cb)) - return; - cbs.push(cb); - bufferMap.set(eventName, cbs); - this.attachedBuffers.set(buffer.id, bufferMap); - return; - } - /** - * Returns `true` if buffer should be detached - */ - detachBufferEvent(buffer, eventName, cb) { - const bufferMap = this.attachedBuffers.get(buffer.id); - if (!bufferMap || !bufferMap.has(eventName)) - return; - const handlers = bufferMap.get(eventName).filter(handler => handler !== cb); - bufferMap.set(eventName, handlers); - } - pauseNotification() { - this.transport.pauseNotification(); - let pauseLevel = this.transport.pauseLevel; - let stack = Error().stack; - let timer = setTimeout(() => { - if (this.transport.pauseLevel >= pauseLevel) { - this.transport.cancelNotification(); - logger.error(`pauseNotification not finished after 1s`, stack); - } - }, 2000); - this.timers.set(pauseLevel, timer); - } - resumeNotification(cancel, notify) { - let { pauseLevel } = this.transport; - let timer = this.timers.get(pauseLevel); - if (timer) { - this.timers.delete(pauseLevel); - clearTimeout(timer); - } - if (cancel) - return Promise.resolve(this.transport.cancelNotification()); - if (notify) { - return Promise.resolve(this.transport.resumeNotification(true)); - } - return Promise.resolve(this.transport.resumeNotification()); - } - hasFunction(name) { - if (!this.functions) - return true; - return this.functions.indexOf(name) !== -1; - } -} -exports.NeovimClient = NeovimClient; - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NvimTransport = void 0; -const msgpack = __importStar(__webpack_require__(160)); -const buffered_1 = __importDefault(__webpack_require__(194)); -const types_1 = __webpack_require__(195); -const base_1 = __importDefault(__webpack_require__(202)); -class NvimTransport extends base_1.default { - constructor(logger) { - super(logger); - this.pending = new Map(); - this.nextRequestId = 1; - this.attached = false; - const codec = this.setupCodec(); - this.encodeStream = msgpack.createEncodeStream({ codec }); - this.decodeStream = msgpack.createDecodeStream({ codec }); - this.decodeStream.on('data', (msg) => { - this.parseMessage(msg); - }); - this.decodeStream.on('end', () => { - this.detach(); - this.emit('detach'); - }); - } - parseMessage(msg) { - const msgType = msg[0]; - this.debugMessage(msg); - if (msgType === 0) { - // request - // - msg[1]: id - // - msg[2]: method name - // - msg[3]: arguments - this.emit('request', msg[2].toString(), msg[3], this.createResponse(msg[1])); - } - else if (msgType === 1) { - // response to a previous request: - // - msg[1]: the id - // - msg[2]: error(if any) - // - msg[3]: result(if not errored) - const id = msg[1]; - const handler = this.pending.get(id); - if (handler) { - this.pending.delete(id); - let err = msg[2]; - if (err && err.length != 2) { - err = [0, err instanceof Error ? err.message : err]; - } - handler(err, msg[3]); - } - } - else if (msgType === 2) { - // notification/event - // - msg[1]: event name - // - msg[2]: arguments - this.emit('notification', msg[1].toString(), msg[2]); - } - else { - // tslint:disable-next-line: no-console - console.error(`Invalid message type ${msgType}`); - } - } - setupCodec() { - const codec = msgpack.createCodec(); - types_1.Metadata.forEach(({ constructor }, id) => { - codec.addExtPacker(id, constructor, (obj) => msgpack.encode(obj.data)); - codec.addExtUnpacker(id, data => new constructor({ - transport: this, - client: this.client, - data: msgpack.decode(data), - })); - }); - this.codec = codec; - return this.codec; - } - attach(writer, reader, client) { - this.encodeStream = this.encodeStream.pipe(writer); - const buffered = new buffered_1.default(); - reader.pipe(buffered).pipe(this.decodeStream); - this.writer = writer; - this.reader = reader; - this.client = client; - this.attached = true; - } - detach() { - if (!this.attached) - return; - this.attached = false; - this.encodeStream.unpipe(this.writer); - this.reader.unpipe(this.decodeStream); - } - request(method, args, cb) { - if (!this.attached) - return; - let id = this.nextRequestId; - this.nextRequestId = this.nextRequestId + 1; - let startTs = Date.now(); - this.debug('request to nvim:', id, method, args); - this.encodeStream.write(msgpack.encode([0, id, method, args], { - codec: this.codec, - })); - let timer = setTimeout(() => { - this.debug(`request to nvim cost more than 1s`, method, args); - }, 1000); - this.pending.set(id, (err, res) => { - clearTimeout(timer); - this.debug('response of nvim:', id, `${Date.now() - startTs}ms`, res, err); - cb(err, res); - }); - } - notify(method, args) { - if (!this.attached) - return; - if (this.pauseLevel != 0) { - let arr = this.paused.get(this.pauseLevel); - if (arr) { - arr.push([method, args]); - return; - } - } - this.debug('nvim notification:', method, args); - this.encodeStream.write(msgpack.encode([2, method, args], { - codec: this.codec, - })); - } - send(arr) { - this.encodeStream.write(msgpack.encode(arr, { - codec: this.codec, - })); - } - createResponse(requestId) { - let { encodeStream } = this; - let startTs = Date.now(); - let called = false; - let timer = setTimeout(() => { - this.debug(`request to client cost more than 1s`, requestId); - }, 1000); - return { - send: (resp, isError) => { - clearTimeout(timer); - if (called || !this.attached) - return; - this.debug('response of client:', requestId, `${Date.now() - startTs}ms`, resp, isError == true); - called = true; - encodeStream.write(msgpack.encode([ - 1, - requestId, - isError ? resp : null, - !isError ? resp : null, - ])); - } - }; - } -} -exports.NvimTransport = NvimTransport; - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - -// msgpack.js - -exports.encode = __webpack_require__(161).encode; -exports.decode = __webpack_require__(181).decode; - -exports.Encoder = __webpack_require__(187).Encoder; -exports.Decoder = __webpack_require__(189).Decoder; - -exports.createEncodeStream = __webpack_require__(190).createEncodeStream; -exports.createDecodeStream = __webpack_require__(191).createDecodeStream; - -exports.createCodec = __webpack_require__(192).createCodec; -exports.codec = __webpack_require__(193).codec; - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - -// encode.js - -exports.encode = encode; - -var EncodeBuffer = __webpack_require__(162).EncodeBuffer; - -function encode(input, options) { - var encoder = new EncodeBuffer(options); - encoder.write(input); - return encoder.read(); -} - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - -// encode-buffer.js - -exports.EncodeBuffer = EncodeBuffer; - -var preset = __webpack_require__(163).preset; - -var FlexEncoder = __webpack_require__(180).FlexEncoder; - -FlexEncoder.mixin(EncodeBuffer.prototype); - -function EncodeBuffer(options) { - if (!(this instanceof EncodeBuffer)) return new EncodeBuffer(options); - - if (options) { - this.options = options; - if (options.codec) { - var codec = this.codec = options.codec; - if (codec.bufferish) this.bufferish = codec.bufferish; - } - } -} - -EncodeBuffer.prototype.codec = preset; - -EncodeBuffer.prototype.write = function(input) { - this.codec.encode(this, input); -}; - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - -// write-core.js - -var ExtBuffer = __webpack_require__(164).ExtBuffer; -var ExtPacker = __webpack_require__(173); -var WriteType = __webpack_require__(174); -var CodecBase = __webpack_require__(179); - -CodecBase.install({ - addExtPacker: addExtPacker, - getExtPacker: getExtPacker, - init: init -}); - -exports.preset = init.call(CodecBase.preset); - -function getEncoder(options) { - var writeType = WriteType.getWriteType(options); - return encode; - - function encode(encoder, value) { - var func = writeType[typeof value]; - if (!func) throw new Error("Unsupported type \"" + (typeof value) + "\": " + value); - func(encoder, value); - } -} - -function init() { - var options = this.options; - this.encode = getEncoder(options); - - if (options && options.preset) { - ExtPacker.setExtPackers(this); - } - - return this; -} - -function addExtPacker(etype, Class, packer) { - packer = CodecBase.filter(packer); - var name = Class.name; - if (name && name !== "Object") { - var packers = this.extPackers || (this.extPackers = {}); - packers[name] = extPacker; - } else { - // fallback for IE - var list = this.extEncoderList || (this.extEncoderList = []); - list.unshift([Class, extPacker]); - } - - function extPacker(value) { - if (packer) value = packer(value); - return new ExtBuffer(value, etype); - } -} - -function getExtPacker(value) { - var packers = this.extPackers || (this.extPackers = {}); - var c = value.constructor; - var e = c && c.name && packers[c.name]; - if (e) return e; - - // fallback for IE - var list = this.extEncoderList || (this.extEncoderList = []); - var len = list.length; - for (var i = 0; i < len; i++) { - var pair = list[i]; - if (c === pair[0]) return pair[1]; - } -} - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - -// ext-buffer.js - -exports.ExtBuffer = ExtBuffer; - -var Bufferish = __webpack_require__(165); - -function ExtBuffer(buffer, type) { - if (!(this instanceof ExtBuffer)) return new ExtBuffer(buffer, type); - this.buffer = Bufferish.from(buffer); - this.type = type; -} - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - -// bufferish.js - -var Buffer = exports.global = __webpack_require__(166); -var hasBuffer = exports.hasBuffer = Buffer && !!Buffer.isBuffer; -var hasArrayBuffer = exports.hasArrayBuffer = ("undefined" !== typeof ArrayBuffer); - -var isArray = exports.isArray = __webpack_require__(167); -exports.isArrayBuffer = hasArrayBuffer ? isArrayBuffer : _false; -var isBuffer = exports.isBuffer = hasBuffer ? Buffer.isBuffer : _false; -var isView = exports.isView = hasArrayBuffer ? (ArrayBuffer.isView || _is("ArrayBuffer", "buffer")) : _false; - -exports.alloc = alloc; -exports.concat = concat; -exports.from = from; - -var BufferArray = exports.Array = __webpack_require__(168); -var BufferBuffer = exports.Buffer = __webpack_require__(169); -var BufferUint8Array = exports.Uint8Array = __webpack_require__(170); -var BufferProto = exports.prototype = __webpack_require__(171); - -/** - * @param value {Array|ArrayBuffer|Buffer|String} - * @returns {Buffer|Uint8Array|Array} - */ - -function from(value) { - if (typeof value === "string") { - return fromString.call(this, value); - } else { - return auto(this).from(value); - } -} - -/** - * @param size {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function alloc(size) { - return auto(this).alloc(size); -} - -/** - * @param list {Array} array of (Buffer|Uint8Array|Array)s - * @param [length] - * @returns {Buffer|Uint8Array|Array} - */ - -function concat(list, length) { - if (!length) { - length = 0; - Array.prototype.forEach.call(list, dryrun); - } - var ref = (this !== exports) && this || list[0]; - var result = alloc.call(ref, length); - var offset = 0; - Array.prototype.forEach.call(list, append); - return result; - - function dryrun(buffer) { - length += buffer.length; - } - - function append(buffer) { - offset += BufferProto.copy.call(buffer, result, offset); - } -} - -var _isArrayBuffer = _is("ArrayBuffer"); - -function isArrayBuffer(value) { - return (value instanceof ArrayBuffer) || _isArrayBuffer(value); -} - -/** - * @private - */ - -function fromString(value) { - var expected = value.length * 3; - var that = alloc.call(this, expected); - var actual = BufferProto.write.call(that, value); - if (expected !== actual) { - that = BufferProto.slice.call(that, 0, actual); - } - return that; -} - -function auto(that) { - return isBuffer(that) ? BufferBuffer - : isView(that) ? BufferUint8Array - : isArray(that) ? BufferArray - : hasBuffer ? BufferBuffer - : hasArrayBuffer ? BufferUint8Array - : BufferArray; -} - -function _false() { - return false; -} - -function _is(name, key) { - /* jshint eqnull:true */ - name = "[object " + name + "]"; - return function(value) { - return (value != null) && {}.toString.call(key ? value[key] : value) === name; - }; -} - -/***/ }), -/* 166 */ -/***/ (function(module, exports) { - -/* globals Buffer */ - -module.exports = - c(("undefined" !== typeof Buffer) && Buffer) || - c(this.Buffer) || - c(("undefined" !== typeof window) && window.Buffer) || - this.Buffer; - -function c(B) { - return B && B.isBuffer && B; -} - -/***/ }), -/* 167 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - -// bufferish-array.js - -var Bufferish = __webpack_require__(165); - -var exports = module.exports = alloc(0); - -exports.alloc = alloc; -exports.concat = Bufferish.concat; -exports.from = from; - -/** - * @param size {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function alloc(size) { - return new Array(size); -} - -/** - * @param value {Array|ArrayBuffer|Buffer|String} - * @returns {Array} - */ - -function from(value) { - if (!Bufferish.isBuffer(value) && Bufferish.isView(value)) { - // TypedArray to Uint8Array - value = Bufferish.Uint8Array.from(value); - } else if (Bufferish.isArrayBuffer(value)) { - // ArrayBuffer to Uint8Array - value = new Uint8Array(value); - } else if (typeof value === "string") { - // String to Array - return Bufferish.from.call(exports, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - - // Array-like to Array - return Array.prototype.slice.call(value); -} - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - -// bufferish-buffer.js - -var Bufferish = __webpack_require__(165); -var Buffer = Bufferish.global; - -var exports = module.exports = Bufferish.hasBuffer ? alloc(0) : []; - -exports.alloc = Bufferish.hasBuffer && Buffer.alloc || alloc; -exports.concat = Bufferish.concat; -exports.from = from; - -/** - * @param size {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function alloc(size) { - return new Buffer(size); -} - -/** - * @param value {Array|ArrayBuffer|Buffer|String} - * @returns {Buffer} - */ - -function from(value) { - if (!Bufferish.isBuffer(value) && Bufferish.isView(value)) { - // TypedArray to Uint8Array - value = Bufferish.Uint8Array.from(value); - } else if (Bufferish.isArrayBuffer(value)) { - // ArrayBuffer to Uint8Array - value = new Uint8Array(value); - } else if (typeof value === "string") { - // String to Buffer - return Bufferish.from.call(exports, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - - // Array-like to Buffer - if (Buffer.from && Buffer.from.length !== 1) { - return Buffer.from(value); // node v6+ - } else { - return new Buffer(value); // node v4 - } -} - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - -// bufferish-uint8array.js - -var Bufferish = __webpack_require__(165); - -var exports = module.exports = Bufferish.hasArrayBuffer ? alloc(0) : []; - -exports.alloc = alloc; -exports.concat = Bufferish.concat; -exports.from = from; - -/** - * @param size {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function alloc(size) { - return new Uint8Array(size); -} - -/** - * @param value {Array|ArrayBuffer|Buffer|String} - * @returns {Uint8Array} - */ - -function from(value) { - if (Bufferish.isView(value)) { - // TypedArray to ArrayBuffer - var byteOffset = value.byteOffset; - var byteLength = value.byteLength; - value = value.buffer; - if (value.byteLength !== byteLength) { - if (value.slice) { - value = value.slice(byteOffset, byteOffset + byteLength); - } else { - // Android 4.1 does not have ArrayBuffer.prototype.slice - value = new Uint8Array(value); - if (value.byteLength !== byteLength) { - // TypedArray to ArrayBuffer to Uint8Array to Array - value = Array.prototype.slice.call(value, byteOffset, byteOffset + byteLength); - } - } - } - } else if (typeof value === "string") { - // String to Uint8Array - return Bufferish.from.call(exports, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - - return new Uint8Array(value); -} - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - -// bufferish-proto.js - -/* jshint eqnull:true */ - -var BufferLite = __webpack_require__(172); - -exports.copy = copy; -exports.slice = slice; -exports.toString = toString; -exports.write = gen("write"); - -var Bufferish = __webpack_require__(165); -var Buffer = Bufferish.global; - -var isBufferShim = Bufferish.hasBuffer && ("TYPED_ARRAY_SUPPORT" in Buffer); -var brokenTypedArray = isBufferShim && !Buffer.TYPED_ARRAY_SUPPORT; - -/** - * @param target {Buffer|Uint8Array|Array} - * @param [targetStart] {Number} - * @param [start] {Number} - * @param [end] {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function copy(target, targetStart, start, end) { - var thisIsBuffer = Bufferish.isBuffer(this); - var targetIsBuffer = Bufferish.isBuffer(target); - if (thisIsBuffer && targetIsBuffer) { - // Buffer to Buffer - return this.copy(target, targetStart, start, end); - } else if (!brokenTypedArray && !thisIsBuffer && !targetIsBuffer && - Bufferish.isView(this) && Bufferish.isView(target)) { - // Uint8Array to Uint8Array (except for minor some browsers) - var buffer = (start || end != null) ? slice.call(this, start, end) : this; - target.set(buffer, targetStart); - return buffer.length; - } else { - // other cases - return BufferLite.copy.call(this, target, targetStart, start, end); - } -} - -/** - * @param [start] {Number} - * @param [end] {Number} - * @returns {Buffer|Uint8Array|Array} - */ - -function slice(start, end) { - // for Buffer, Uint8Array (except for minor some browsers) and Array - var f = this.slice || (!brokenTypedArray && this.subarray); - if (f) return f.call(this, start, end); - - // Uint8Array (for minor some browsers) - var target = Bufferish.alloc.call(this, end - start); - copy.call(this, target, 0, start, end); - return target; -} - -/** - * Buffer.prototype.toString() - * - * @param [encoding] {String} ignored - * @param [start] {Number} - * @param [end] {Number} - * @returns {String} - */ - -function toString(encoding, start, end) { - var f = (!isBufferShim && Bufferish.isBuffer(this)) ? this.toString : BufferLite.toString; - return f.apply(this, arguments); -} - -/** - * @private - */ - -function gen(method) { - return wrap; - - function wrap() { - var f = this[method] || BufferLite[method]; - return f.apply(this, arguments); - } -} - - -/***/ }), -/* 172 */ -/***/ (function(module, exports) { - -// buffer-lite.js - -var MAXBUFLEN = 8192; - -exports.copy = copy; -exports.toString = toString; -exports.write = write; - -/** - * Buffer.prototype.write() - * - * @param string {String} - * @param [offset] {Number} - * @returns {Number} - */ - -function write(string, offset) { - var buffer = this; - var index = offset || (offset |= 0); - var length = string.length; - var chr = 0; - var i = 0; - while (i < length) { - chr = string.charCodeAt(i++); - - if (chr < 128) { - buffer[index++] = chr; - } else if (chr < 0x800) { - // 2 bytes - buffer[index++] = 0xC0 | (chr >>> 6); - buffer[index++] = 0x80 | (chr & 0x3F); - } else if (chr < 0xD800 || chr > 0xDFFF) { - // 3 bytes - buffer[index++] = 0xE0 | (chr >>> 12); - buffer[index++] = 0x80 | ((chr >>> 6) & 0x3F); - buffer[index++] = 0x80 | (chr & 0x3F); - } else { - // 4 bytes - surrogate pair - chr = (((chr - 0xD800) << 10) | (string.charCodeAt(i++) - 0xDC00)) + 0x10000; - buffer[index++] = 0xF0 | (chr >>> 18); - buffer[index++] = 0x80 | ((chr >>> 12) & 0x3F); - buffer[index++] = 0x80 | ((chr >>> 6) & 0x3F); - buffer[index++] = 0x80 | (chr & 0x3F); - } - } - return index - offset; -} - -/** - * Buffer.prototype.toString() - * - * @param [encoding] {String} ignored - * @param [start] {Number} - * @param [end] {Number} - * @returns {String} - */ - -function toString(encoding, start, end) { - var buffer = this; - var index = start|0; - if (!end) end = buffer.length; - var string = ''; - var chr = 0; - - while (index < end) { - chr = buffer[index++]; - if (chr < 128) { - string += String.fromCharCode(chr); - continue; - } - - if ((chr & 0xE0) === 0xC0) { - // 2 bytes - chr = (chr & 0x1F) << 6 | - (buffer[index++] & 0x3F); - - } else if ((chr & 0xF0) === 0xE0) { - // 3 bytes - chr = (chr & 0x0F) << 12 | - (buffer[index++] & 0x3F) << 6 | - (buffer[index++] & 0x3F); - - } else if ((chr & 0xF8) === 0xF0) { - // 4 bytes - chr = (chr & 0x07) << 18 | - (buffer[index++] & 0x3F) << 12 | - (buffer[index++] & 0x3F) << 6 | - (buffer[index++] & 0x3F); - } - - if (chr >= 0x010000) { - // A surrogate pair - chr -= 0x010000; - - string += String.fromCharCode((chr >>> 10) + 0xD800, (chr & 0x3FF) + 0xDC00); - } else { - string += String.fromCharCode(chr); - } - } - - return string; -} - -/** - * Buffer.prototype.copy() - * - * @param target {Buffer} - * @param [targetStart] {Number} - * @param [start] {Number} - * @param [end] {Number} - * @returns {number} - */ - -function copy(target, targetStart, start, end) { - var i; - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (!targetStart) targetStart = 0; - var len = end - start; - - if (target === this && start < targetStart && targetStart < end) { - // descending - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start]; - } - } else { - // ascending - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start]; - } - } - - return len; -} - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - -// ext-packer.js - -exports.setExtPackers = setExtPackers; - -var Bufferish = __webpack_require__(165); -var Buffer = Bufferish.global; -var packTypedArray = Bufferish.Uint8Array.from; -var _encode; - -var ERROR_COLUMNS = {name: 1, message: 1, stack: 1, columnNumber: 1, fileName: 1, lineNumber: 1}; - -function setExtPackers(codec) { - codec.addExtPacker(0x0E, Error, [packError, encode]); - codec.addExtPacker(0x01, EvalError, [packError, encode]); - codec.addExtPacker(0x02, RangeError, [packError, encode]); - codec.addExtPacker(0x03, ReferenceError, [packError, encode]); - codec.addExtPacker(0x04, SyntaxError, [packError, encode]); - codec.addExtPacker(0x05, TypeError, [packError, encode]); - codec.addExtPacker(0x06, URIError, [packError, encode]); - - codec.addExtPacker(0x0A, RegExp, [packRegExp, encode]); - codec.addExtPacker(0x0B, Boolean, [packValueOf, encode]); - codec.addExtPacker(0x0C, String, [packValueOf, encode]); - codec.addExtPacker(0x0D, Date, [Number, encode]); - codec.addExtPacker(0x0F, Number, [packValueOf, encode]); - - if ("undefined" !== typeof Uint8Array) { - codec.addExtPacker(0x11, Int8Array, packTypedArray); - codec.addExtPacker(0x12, Uint8Array, packTypedArray); - codec.addExtPacker(0x13, Int16Array, packTypedArray); - codec.addExtPacker(0x14, Uint16Array, packTypedArray); - codec.addExtPacker(0x15, Int32Array, packTypedArray); - codec.addExtPacker(0x16, Uint32Array, packTypedArray); - codec.addExtPacker(0x17, Float32Array, packTypedArray); - - // PhantomJS/1.9.7 doesn't have Float64Array - if ("undefined" !== typeof Float64Array) { - codec.addExtPacker(0x18, Float64Array, packTypedArray); - } - - // IE10 doesn't have Uint8ClampedArray - if ("undefined" !== typeof Uint8ClampedArray) { - codec.addExtPacker(0x19, Uint8ClampedArray, packTypedArray); - } - - codec.addExtPacker(0x1A, ArrayBuffer, packTypedArray); - codec.addExtPacker(0x1D, DataView, packTypedArray); - } - - if (Bufferish.hasBuffer) { - codec.addExtPacker(0x1B, Buffer, Bufferish.from); - } -} - -function encode(input) { - if (!_encode) _encode = __webpack_require__(161).encode; // lazy load - return _encode(input); -} - -function packValueOf(value) { - return (value).valueOf(); -} - -function packRegExp(value) { - value = RegExp.prototype.toString.call(value).split("/"); - value.shift(); - var out = [value.pop()]; - out.unshift(value.join("/")); - return out; -} - -function packError(value) { - var out = {}; - for (var key in ERROR_COLUMNS) { - out[key] = value[key]; - } - return out; -} - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - -// write-type.js - -var IS_ARRAY = __webpack_require__(167); -var Int64Buffer = __webpack_require__(175); -var Uint64BE = Int64Buffer.Uint64BE; -var Int64BE = Int64Buffer.Int64BE; - -var Bufferish = __webpack_require__(165); -var BufferProto = __webpack_require__(171); -var WriteToken = __webpack_require__(176); -var uint8 = __webpack_require__(178).uint8; -var ExtBuffer = __webpack_require__(164).ExtBuffer; - -var HAS_UINT8ARRAY = ("undefined" !== typeof Uint8Array); -var HAS_MAP = ("undefined" !== typeof Map); - -var extmap = []; -extmap[1] = 0xd4; -extmap[2] = 0xd5; -extmap[4] = 0xd6; -extmap[8] = 0xd7; -extmap[16] = 0xd8; - -exports.getWriteType = getWriteType; - -function getWriteType(options) { - var token = WriteToken.getWriteToken(options); - var useraw = options && options.useraw; - var binarraybuffer = HAS_UINT8ARRAY && options && options.binarraybuffer; - var isBuffer = binarraybuffer ? Bufferish.isArrayBuffer : Bufferish.isBuffer; - var bin = binarraybuffer ? bin_arraybuffer : bin_buffer; - var usemap = HAS_MAP && options && options.usemap; - var map = usemap ? map_to_map : obj_to_map; - - var writeType = { - "boolean": bool, - "function": nil, - "number": number, - "object": (useraw ? object_raw : object), - "string": _string(useraw ? raw_head_size : str_head_size), - "symbol": nil, - "undefined": nil - }; - - return writeType; - - // false -- 0xc2 - // true -- 0xc3 - function bool(encoder, value) { - var type = value ? 0xc3 : 0xc2; - token[type](encoder, value); - } - - function number(encoder, value) { - var ivalue = value | 0; - var type; - if (value !== ivalue) { - // float 64 -- 0xcb - type = 0xcb; - token[type](encoder, value); - return; - } else if (-0x20 <= ivalue && ivalue <= 0x7F) { - // positive fixint -- 0x00 - 0x7f - // negative fixint -- 0xe0 - 0xff - type = ivalue & 0xFF; - } else if (0 <= ivalue) { - // uint 8 -- 0xcc - // uint 16 -- 0xcd - // uint 32 -- 0xce - type = (ivalue <= 0xFF) ? 0xcc : (ivalue <= 0xFFFF) ? 0xcd : 0xce; - } else { - // int 8 -- 0xd0 - // int 16 -- 0xd1 - // int 32 -- 0xd2 - type = (-0x80 <= ivalue) ? 0xd0 : (-0x8000 <= ivalue) ? 0xd1 : 0xd2; - } - token[type](encoder, ivalue); - } - - // uint 64 -- 0xcf - function uint64(encoder, value) { - var type = 0xcf; - token[type](encoder, value.toArray()); - } - - // int 64 -- 0xd3 - function int64(encoder, value) { - var type = 0xd3; - token[type](encoder, value.toArray()); - } - - // str 8 -- 0xd9 - // str 16 -- 0xda - // str 32 -- 0xdb - // fixstr -- 0xa0 - 0xbf - function str_head_size(length) { - return (length < 32) ? 1 : (length <= 0xFF) ? 2 : (length <= 0xFFFF) ? 3 : 5; - } - - // raw 16 -- 0xda - // raw 32 -- 0xdb - // fixraw -- 0xa0 - 0xbf - function raw_head_size(length) { - return (length < 32) ? 1 : (length <= 0xFFFF) ? 3 : 5; - } - - function _string(head_size) { - return string; - - function string(encoder, value) { - // prepare buffer - var length = value.length; - var maxsize = 5 + length * 3; - encoder.offset = encoder.reserve(maxsize); - var buffer = encoder.buffer; - - // expected header size - var expected = head_size(length); - - // expected start point - var start = encoder.offset + expected; - - // write string - length = BufferProto.write.call(buffer, value, start); - - // actual header size - var actual = head_size(length); - - // move content when needed - if (expected !== actual) { - var targetStart = start + actual - expected; - var end = start + length; - BufferProto.copy.call(buffer, buffer, targetStart, start, end); - } - - // write header - var type = (actual === 1) ? (0xa0 + length) : (actual <= 3) ? (0xd7 + actual) : 0xdb; - token[type](encoder, length); - - // move cursor - encoder.offset += length; - } - } - - function object(encoder, value) { - // null - if (value === null) return nil(encoder, value); - - // Buffer - if (isBuffer(value)) return bin(encoder, value); - - // Array - if (IS_ARRAY(value)) return array(encoder, value); - - // int64-buffer objects - if (Uint64BE.isUint64BE(value)) return uint64(encoder, value); - if (Int64BE.isInt64BE(value)) return int64(encoder, value); - - // ext formats - var packer = encoder.codec.getExtPacker(value); - if (packer) value = packer(value); - if (value instanceof ExtBuffer) return ext(encoder, value); - - // plain old Objects or Map - map(encoder, value); - } - - function object_raw(encoder, value) { - // Buffer - if (isBuffer(value)) return raw(encoder, value); - - // others - object(encoder, value); - } - - // nil -- 0xc0 - function nil(encoder, value) { - var type = 0xc0; - token[type](encoder, value); - } - - // fixarray -- 0x90 - 0x9f - // array 16 -- 0xdc - // array 32 -- 0xdd - function array(encoder, value) { - var length = value.length; - var type = (length < 16) ? (0x90 + length) : (length <= 0xFFFF) ? 0xdc : 0xdd; - token[type](encoder, length); - - var encode = encoder.codec.encode; - for (var i = 0; i < length; i++) { - encode(encoder, value[i]); - } - } - - // bin 8 -- 0xc4 - // bin 16 -- 0xc5 - // bin 32 -- 0xc6 - function bin_buffer(encoder, value) { - var length = value.length; - var type = (length < 0xFF) ? 0xc4 : (length <= 0xFFFF) ? 0xc5 : 0xc6; - token[type](encoder, length); - encoder.send(value); - } - - function bin_arraybuffer(encoder, value) { - bin_buffer(encoder, new Uint8Array(value)); - } - - // fixext 1 -- 0xd4 - // fixext 2 -- 0xd5 - // fixext 4 -- 0xd6 - // fixext 8 -- 0xd7 - // fixext 16 -- 0xd8 - // ext 8 -- 0xc7 - // ext 16 -- 0xc8 - // ext 32 -- 0xc9 - function ext(encoder, value) { - var buffer = value.buffer; - var length = buffer.length; - var type = extmap[length] || ((length < 0xFF) ? 0xc7 : (length <= 0xFFFF) ? 0xc8 : 0xc9); - token[type](encoder, length); - uint8[value.type](encoder); - encoder.send(buffer); - } - - // fixmap -- 0x80 - 0x8f - // map 16 -- 0xde - // map 32 -- 0xdf - function obj_to_map(encoder, value) { - var keys = Object.keys(value); - var length = keys.length; - var type = (length < 16) ? (0x80 + length) : (length <= 0xFFFF) ? 0xde : 0xdf; - token[type](encoder, length); - - var encode = encoder.codec.encode; - keys.forEach(function(key) { - encode(encoder, key); - encode(encoder, value[key]); - }); - } - - // fixmap -- 0x80 - 0x8f - // map 16 -- 0xde - // map 32 -- 0xdf - function map_to_map(encoder, value) { - if (!(value instanceof Map)) return obj_to_map(encoder, value); - - var length = value.size; - var type = (length < 16) ? (0x80 + length) : (length <= 0xFFFF) ? 0xde : 0xdf; - token[type](encoder, length); - - var encode = encoder.codec.encode; - value.forEach(function(val, key, m) { - encode(encoder, key); - encode(encoder, val); - }); - } - - // raw 16 -- 0xda - // raw 32 -- 0xdb - // fixraw -- 0xa0 - 0xbf - function raw(encoder, value) { - var length = value.length; - var type = (length < 32) ? (0xa0 + length) : (length <= 0xFFFF) ? 0xda : 0xdb; - token[type](encoder, length); - encoder.send(value); - } -} - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - -// int64-buffer.js - -/*jshint -W018 */ // Confusing use of '!'. -/*jshint -W030 */ // Expected an assignment or function call and instead saw an expression. -/*jshint -W093 */ // Did you mean to return a conditional instead of an assignment? - -var Uint64BE, Int64BE, Uint64LE, Int64LE; - -!function(exports) { - // constants - - var UNDEFINED = "undefined"; - var BUFFER = (UNDEFINED !== typeof Buffer) && Buffer; - var UINT8ARRAY = (UNDEFINED !== typeof Uint8Array) && Uint8Array; - var ARRAYBUFFER = (UNDEFINED !== typeof ArrayBuffer) && ArrayBuffer; - var ZERO = [0, 0, 0, 0, 0, 0, 0, 0]; - var isArray = Array.isArray || _isArray; - var BIT32 = 4294967296; - var BIT24 = 16777216; - - // storage class - - var storage; // Array; - - // generate classes - - Uint64BE = factory("Uint64BE", true, true); - Int64BE = factory("Int64BE", true, false); - Uint64LE = factory("Uint64LE", false, true); - Int64LE = factory("Int64LE", false, false); - - // class factory - - function factory(name, bigendian, unsigned) { - var posH = bigendian ? 0 : 4; - var posL = bigendian ? 4 : 0; - var pos0 = bigendian ? 0 : 3; - var pos1 = bigendian ? 1 : 2; - var pos2 = bigendian ? 2 : 1; - var pos3 = bigendian ? 3 : 0; - var fromPositive = bigendian ? fromPositiveBE : fromPositiveLE; - var fromNegative = bigendian ? fromNegativeBE : fromNegativeLE; - var proto = Int64.prototype; - var isName = "is" + name; - var _isInt64 = "_" + isName; - - // properties - proto.buffer = void 0; - proto.offset = 0; - proto[_isInt64] = true; - - // methods - proto.toNumber = toNumber; - proto.toString = toString; - proto.toJSON = toNumber; - proto.toArray = toArray; - - // add .toBuffer() method only when Buffer available - if (BUFFER) proto.toBuffer = toBuffer; - - // add .toArrayBuffer() method only when Uint8Array available - if (UINT8ARRAY) proto.toArrayBuffer = toArrayBuffer; - - // isUint64BE, isInt64BE - Int64[isName] = isInt64; - - // CommonJS - exports[name] = Int64; - - return Int64; - - // constructor - function Int64(buffer, offset, value, raddix) { - if (!(this instanceof Int64)) return new Int64(buffer, offset, value, raddix); - return init(this, buffer, offset, value, raddix); - } - - // isUint64BE, isInt64BE - function isInt64(b) { - return !!(b && b[_isInt64]); - } - - // initializer - function init(that, buffer, offset, value, raddix) { - if (UINT8ARRAY && ARRAYBUFFER) { - if (buffer instanceof ARRAYBUFFER) buffer = new UINT8ARRAY(buffer); - if (value instanceof ARRAYBUFFER) value = new UINT8ARRAY(value); - } - - // Int64BE() style - if (!buffer && !offset && !value && !storage) { - // shortcut to initialize with zero - that.buffer = newArray(ZERO, 0); - return; - } - - // Int64BE(value, raddix) style - if (!isValidBuffer(buffer, offset)) { - var _storage = storage || Array; - raddix = offset; - value = buffer; - offset = 0; - buffer = new _storage(8); - } - - that.buffer = buffer; - that.offset = offset |= 0; - - // Int64BE(buffer, offset) style - if (UNDEFINED === typeof value) return; - - // Int64BE(buffer, offset, value, raddix) style - if ("string" === typeof value) { - fromString(buffer, offset, value, raddix || 10); - } else if (isValidBuffer(value, raddix)) { - fromArray(buffer, offset, value, raddix); - } else if ("number" === typeof raddix) { - writeInt32(buffer, offset + posH, value); // high - writeInt32(buffer, offset + posL, raddix); // low - } else if (value > 0) { - fromPositive(buffer, offset, value); // positive - } else if (value < 0) { - fromNegative(buffer, offset, value); // negative - } else { - fromArray(buffer, offset, ZERO, 0); // zero, NaN and others - } - } - - function fromString(buffer, offset, str, raddix) { - var pos = 0; - var len = str.length; - var high = 0; - var low = 0; - if (str[0] === "-") pos++; - var sign = pos; - while (pos < len) { - var chr = parseInt(str[pos++], raddix); - if (!(chr >= 0)) break; // NaN - low = low * raddix + chr; - high = high * raddix + Math.floor(low / BIT32); - low %= BIT32; - } - if (sign) { - high = ~high; - if (low) { - low = BIT32 - low; - } else { - high++; - } - } - writeInt32(buffer, offset + posH, high); - writeInt32(buffer, offset + posL, low); - } - - function toNumber() { - var buffer = this.buffer; - var offset = this.offset; - var high = readInt32(buffer, offset + posH); - var low = readInt32(buffer, offset + posL); - if (!unsigned) high |= 0; // a trick to get signed - return high ? (high * BIT32 + low) : low; - } - - function toString(radix) { - var buffer = this.buffer; - var offset = this.offset; - var high = readInt32(buffer, offset + posH); - var low = readInt32(buffer, offset + posL); - var str = ""; - var sign = !unsigned && (high & 0x80000000); - if (sign) { - high = ~high; - low = BIT32 - low; - } - radix = radix || 10; - while (1) { - var mod = (high % radix) * BIT32 + low; - high = Math.floor(high / radix); - low = Math.floor(mod / radix); - str = (mod % radix).toString(radix) + str; - if (!high && !low) break; - } - if (sign) { - str = "-" + str; - } - return str; - } - - function writeInt32(buffer, offset, value) { - buffer[offset + pos3] = value & 255; - value = value >> 8; - buffer[offset + pos2] = value & 255; - value = value >> 8; - buffer[offset + pos1] = value & 255; - value = value >> 8; - buffer[offset + pos0] = value & 255; - } - - function readInt32(buffer, offset) { - return (buffer[offset + pos0] * BIT24) + - (buffer[offset + pos1] << 16) + - (buffer[offset + pos2] << 8) + - buffer[offset + pos3]; - } - } - - function toArray(raw) { - var buffer = this.buffer; - var offset = this.offset; - storage = null; // Array - if (raw !== false && offset === 0 && buffer.length === 8 && isArray(buffer)) return buffer; - return newArray(buffer, offset); - } - - function toBuffer(raw) { - var buffer = this.buffer; - var offset = this.offset; - storage = BUFFER; - if (raw !== false && offset === 0 && buffer.length === 8 && Buffer.isBuffer(buffer)) return buffer; - var dest = new BUFFER(8); - fromArray(dest, 0, buffer, offset); - return dest; - } - - function toArrayBuffer(raw) { - var buffer = this.buffer; - var offset = this.offset; - var arrbuf = buffer.buffer; - storage = UINT8ARRAY; - if (raw !== false && offset === 0 && (arrbuf instanceof ARRAYBUFFER) && arrbuf.byteLength === 8) return arrbuf; - var dest = new UINT8ARRAY(8); - fromArray(dest, 0, buffer, offset); - return dest.buffer; - } - - function isValidBuffer(buffer, offset) { - var len = buffer && buffer.length; - offset |= 0; - return len && (offset + 8 <= len) && ("string" !== typeof buffer[offset]); - } - - function fromArray(destbuf, destoff, srcbuf, srcoff) { - destoff |= 0; - srcoff |= 0; - for (var i = 0; i < 8; i++) { - destbuf[destoff++] = srcbuf[srcoff++] & 255; - } - } - - function newArray(buffer, offset) { - return Array.prototype.slice.call(buffer, offset, offset + 8); - } - - function fromPositiveBE(buffer, offset, value) { - var pos = offset + 8; - while (pos > offset) { - buffer[--pos] = value & 255; - value /= 256; - } - } - - function fromNegativeBE(buffer, offset, value) { - var pos = offset + 8; - value++; - while (pos > offset) { - buffer[--pos] = ((-value) & 255) ^ 255; - value /= 256; - } - } - - function fromPositiveLE(buffer, offset, value) { - var end = offset + 8; - while (offset < end) { - buffer[offset++] = value & 255; - value /= 256; - } - } - - function fromNegativeLE(buffer, offset, value) { - var end = offset + 8; - value++; - while (offset < end) { - buffer[offset++] = ((-value) & 255) ^ 255; - value /= 256; - } - } - - // https://github.com/retrofox/is-array - function _isArray(val) { - return !!val && "[object Array]" == Object.prototype.toString.call(val); - } - -}( true && typeof exports.nodeName !== 'string' ? exports : (this || {})); - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - -// write-token.js - -var ieee754 = __webpack_require__(177); -var Int64Buffer = __webpack_require__(175); -var Uint64BE = Int64Buffer.Uint64BE; -var Int64BE = Int64Buffer.Int64BE; - -var uint8 = __webpack_require__(178).uint8; -var Bufferish = __webpack_require__(165); -var Buffer = Bufferish.global; -var IS_BUFFER_SHIM = Bufferish.hasBuffer && ("TYPED_ARRAY_SUPPORT" in Buffer); -var NO_TYPED_ARRAY = IS_BUFFER_SHIM && !Buffer.TYPED_ARRAY_SUPPORT; -var Buffer_prototype = Bufferish.hasBuffer && Buffer.prototype || {}; - -exports.getWriteToken = getWriteToken; - -function getWriteToken(options) { - if (options && options.uint8array) { - return init_uint8array(); - } else if (NO_TYPED_ARRAY || (Bufferish.hasBuffer && options && options.safe)) { - return init_safe(); - } else { - return init_token(); - } -} - -function init_uint8array() { - var token = init_token(); - - // float 32 -- 0xca - // float 64 -- 0xcb - token[0xca] = writeN(0xca, 4, writeFloatBE); - token[0xcb] = writeN(0xcb, 8, writeDoubleBE); - - return token; -} - -// Node.js and browsers with TypedArray - -function init_token() { - // (immediate values) - // positive fixint -- 0x00 - 0x7f - // nil -- 0xc0 - // false -- 0xc2 - // true -- 0xc3 - // negative fixint -- 0xe0 - 0xff - var token = uint8.slice(); - - // bin 8 -- 0xc4 - // bin 16 -- 0xc5 - // bin 32 -- 0xc6 - token[0xc4] = write1(0xc4); - token[0xc5] = write2(0xc5); - token[0xc6] = write4(0xc6); - - // ext 8 -- 0xc7 - // ext 16 -- 0xc8 - // ext 32 -- 0xc9 - token[0xc7] = write1(0xc7); - token[0xc8] = write2(0xc8); - token[0xc9] = write4(0xc9); - - // float 32 -- 0xca - // float 64 -- 0xcb - token[0xca] = writeN(0xca, 4, (Buffer_prototype.writeFloatBE || writeFloatBE), true); - token[0xcb] = writeN(0xcb, 8, (Buffer_prototype.writeDoubleBE || writeDoubleBE), true); - - // uint 8 -- 0xcc - // uint 16 -- 0xcd - // uint 32 -- 0xce - // uint 64 -- 0xcf - token[0xcc] = write1(0xcc); - token[0xcd] = write2(0xcd); - token[0xce] = write4(0xce); - token[0xcf] = writeN(0xcf, 8, writeUInt64BE); - - // int 8 -- 0xd0 - // int 16 -- 0xd1 - // int 32 -- 0xd2 - // int 64 -- 0xd3 - token[0xd0] = write1(0xd0); - token[0xd1] = write2(0xd1); - token[0xd2] = write4(0xd2); - token[0xd3] = writeN(0xd3, 8, writeInt64BE); - - // str 8 -- 0xd9 - // str 16 -- 0xda - // str 32 -- 0xdb - token[0xd9] = write1(0xd9); - token[0xda] = write2(0xda); - token[0xdb] = write4(0xdb); - - // array 16 -- 0xdc - // array 32 -- 0xdd - token[0xdc] = write2(0xdc); - token[0xdd] = write4(0xdd); - - // map 16 -- 0xde - // map 32 -- 0xdf - token[0xde] = write2(0xde); - token[0xdf] = write4(0xdf); - - return token; -} - -// safe mode: for old browsers and who needs asserts - -function init_safe() { - // (immediate values) - // positive fixint -- 0x00 - 0x7f - // nil -- 0xc0 - // false -- 0xc2 - // true -- 0xc3 - // negative fixint -- 0xe0 - 0xff - var token = uint8.slice(); - - // bin 8 -- 0xc4 - // bin 16 -- 0xc5 - // bin 32 -- 0xc6 - token[0xc4] = writeN(0xc4, 1, Buffer.prototype.writeUInt8); - token[0xc5] = writeN(0xc5, 2, Buffer.prototype.writeUInt16BE); - token[0xc6] = writeN(0xc6, 4, Buffer.prototype.writeUInt32BE); - - // ext 8 -- 0xc7 - // ext 16 -- 0xc8 - // ext 32 -- 0xc9 - token[0xc7] = writeN(0xc7, 1, Buffer.prototype.writeUInt8); - token[0xc8] = writeN(0xc8, 2, Buffer.prototype.writeUInt16BE); - token[0xc9] = writeN(0xc9, 4, Buffer.prototype.writeUInt32BE); - - // float 32 -- 0xca - // float 64 -- 0xcb - token[0xca] = writeN(0xca, 4, Buffer.prototype.writeFloatBE); - token[0xcb] = writeN(0xcb, 8, Buffer.prototype.writeDoubleBE); - - // uint 8 -- 0xcc - // uint 16 -- 0xcd - // uint 32 -- 0xce - // uint 64 -- 0xcf - token[0xcc] = writeN(0xcc, 1, Buffer.prototype.writeUInt8); - token[0xcd] = writeN(0xcd, 2, Buffer.prototype.writeUInt16BE); - token[0xce] = writeN(0xce, 4, Buffer.prototype.writeUInt32BE); - token[0xcf] = writeN(0xcf, 8, writeUInt64BE); - - // int 8 -- 0xd0 - // int 16 -- 0xd1 - // int 32 -- 0xd2 - // int 64 -- 0xd3 - token[0xd0] = writeN(0xd0, 1, Buffer.prototype.writeInt8); - token[0xd1] = writeN(0xd1, 2, Buffer.prototype.writeInt16BE); - token[0xd2] = writeN(0xd2, 4, Buffer.prototype.writeInt32BE); - token[0xd3] = writeN(0xd3, 8, writeInt64BE); - - // str 8 -- 0xd9 - // str 16 -- 0xda - // str 32 -- 0xdb - token[0xd9] = writeN(0xd9, 1, Buffer.prototype.writeUInt8); - token[0xda] = writeN(0xda, 2, Buffer.prototype.writeUInt16BE); - token[0xdb] = writeN(0xdb, 4, Buffer.prototype.writeUInt32BE); - - // array 16 -- 0xdc - // array 32 -- 0xdd - token[0xdc] = writeN(0xdc, 2, Buffer.prototype.writeUInt16BE); - token[0xdd] = writeN(0xdd, 4, Buffer.prototype.writeUInt32BE); - - // map 16 -- 0xde - // map 32 -- 0xdf - token[0xde] = writeN(0xde, 2, Buffer.prototype.writeUInt16BE); - token[0xdf] = writeN(0xdf, 4, Buffer.prototype.writeUInt32BE); - - return token; -} - -function write1(type) { - return function(encoder, value) { - var offset = encoder.reserve(2); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset] = value; - }; -} - -function write2(type) { - return function(encoder, value) { - var offset = encoder.reserve(3); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset++] = value >>> 8; - buffer[offset] = value; - }; -} - -function write4(type) { - return function(encoder, value) { - var offset = encoder.reserve(5); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset++] = value >>> 24; - buffer[offset++] = value >>> 16; - buffer[offset++] = value >>> 8; - buffer[offset] = value; - }; -} - -function writeN(type, len, method, noAssert) { - return function(encoder, value) { - var offset = encoder.reserve(len + 1); - encoder.buffer[offset++] = type; - method.call(encoder.buffer, value, offset, noAssert); - }; -} - -function writeUInt64BE(value, offset) { - new Uint64BE(this, offset, value); -} - -function writeInt64BE(value, offset) { - new Int64BE(this, offset, value); -} - -function writeFloatBE(value, offset) { - ieee754.write(this, value, offset, false, 23, 4); -} - -function writeDoubleBE(value, offset) { - ieee754.write(this, value, offset, false, 52, 8); -} - - -/***/ }), -/* 177 */ -/***/ (function(module, exports) { - -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - - -/***/ }), -/* 178 */ -/***/ (function(module, exports) { - -// write-unit8.js - -var constant = exports.uint8 = new Array(256); - -for (var i = 0x00; i <= 0xFF; i++) { - constant[i] = write0(i); -} - -function write0(type) { - return function(encoder) { - var offset = encoder.reserve(1); - encoder.buffer[offset] = type; - }; -} - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - -// codec-base.js - -var IS_ARRAY = __webpack_require__(167); - -exports.createCodec = createCodec; -exports.install = install; -exports.filter = filter; - -var Bufferish = __webpack_require__(165); - -function Codec(options) { - if (!(this instanceof Codec)) return new Codec(options); - this.options = options; - this.init(); -} - -Codec.prototype.init = function() { - var options = this.options; - - if (options && options.uint8array) { - this.bufferish = Bufferish.Uint8Array; - } - - return this; -}; - -function install(props) { - for (var key in props) { - Codec.prototype[key] = add(Codec.prototype[key], props[key]); - } -} - -function add(a, b) { - return (a && b) ? ab : (a || b); - - function ab() { - a.apply(this, arguments); - return b.apply(this, arguments); - } -} - -function join(filters) { - filters = filters.slice(); - - return function(value) { - return filters.reduce(iterator, value); - }; - - function iterator(value, filter) { - return filter(value); - } -} - -function filter(filter) { - return IS_ARRAY(filter) ? join(filter) : filter; -} - -// @public -// msgpack.createCodec() - -function createCodec(options) { - return new Codec(options); -} - -// default shared codec - -exports.preset = createCodec({preset: true}); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - -// flex-buffer.js - -exports.FlexDecoder = FlexDecoder; -exports.FlexEncoder = FlexEncoder; - -var Bufferish = __webpack_require__(165); - -var MIN_BUFFER_SIZE = 2048; -var MAX_BUFFER_SIZE = 65536; -var BUFFER_SHORTAGE = "BUFFER_SHORTAGE"; - -function FlexDecoder() { - if (!(this instanceof FlexDecoder)) return new FlexDecoder(); -} - -function FlexEncoder() { - if (!(this instanceof FlexEncoder)) return new FlexEncoder(); -} - -FlexDecoder.mixin = mixinFactory(getDecoderMethods()); -FlexDecoder.mixin(FlexDecoder.prototype); - -FlexEncoder.mixin = mixinFactory(getEncoderMethods()); -FlexEncoder.mixin(FlexEncoder.prototype); - -function getDecoderMethods() { - return { - bufferish: Bufferish, - write: write, - fetch: fetch, - flush: flush, - push: push, - pull: pull, - read: read, - reserve: reserve, - offset: 0 - }; - - function write(chunk) { - var prev = this.offset ? Bufferish.prototype.slice.call(this.buffer, this.offset) : this.buffer; - this.buffer = prev ? (chunk ? this.bufferish.concat([prev, chunk]) : prev) : chunk; - this.offset = 0; - } - - function flush() { - while (this.offset < this.buffer.length) { - var start = this.offset; - var value; - try { - value = this.fetch(); - } catch (e) { - if (e && e.message != BUFFER_SHORTAGE) throw e; - // rollback - this.offset = start; - break; - } - this.push(value); - } - } - - function reserve(length) { - var start = this.offset; - var end = start + length; - if (end > this.buffer.length) throw new Error(BUFFER_SHORTAGE); - this.offset = end; - return start; - } -} - -function getEncoderMethods() { - return { - bufferish: Bufferish, - write: write, - fetch: fetch, - flush: flush, - push: push, - pull: pull, - read: read, - reserve: reserve, - send: send, - maxBufferSize: MAX_BUFFER_SIZE, - minBufferSize: MIN_BUFFER_SIZE, - offset: 0, - start: 0 - }; - - function fetch() { - var start = this.start; - if (start < this.offset) { - var end = this.start = this.offset; - return Bufferish.prototype.slice.call(this.buffer, start, end); - } - } - - function flush() { - while (this.start < this.offset) { - var value = this.fetch(); - if (value) this.push(value); - } - } - - function pull() { - var buffers = this.buffers || (this.buffers = []); - var chunk = buffers.length > 1 ? this.bufferish.concat(buffers) : buffers[0]; - buffers.length = 0; // buffer exhausted - return chunk; - } - - function reserve(length) { - var req = length | 0; - - if (this.buffer) { - var size = this.buffer.length; - var start = this.offset | 0; - var end = start + req; - - // is it long enough? - if (end < size) { - this.offset = end; - return start; - } - - // flush current buffer - this.flush(); - - // resize it to 2x current length - length = Math.max(length, Math.min(size * 2, this.maxBufferSize)); - } - - // minimum buffer size - length = Math.max(length, this.minBufferSize); - - // allocate new buffer - this.buffer = this.bufferish.alloc(length); - this.start = 0; - this.offset = req; - return 0; - } - - function send(buffer) { - var length = buffer.length; - if (length > this.minBufferSize) { - this.flush(); - this.push(buffer); - } else { - var offset = this.reserve(length); - Bufferish.prototype.copy.call(buffer, this.buffer, offset); - } - } -} - -// common methods - -function write() { - throw new Error("method not implemented: write()"); -} - -function fetch() { - throw new Error("method not implemented: fetch()"); -} - -function read() { - var length = this.buffers && this.buffers.length; - - // fetch the first result - if (!length) return this.fetch(); - - // flush current buffer - this.flush(); - - // read from the results - return this.pull(); -} - -function push(chunk) { - var buffers = this.buffers || (this.buffers = []); - buffers.push(chunk); -} - -function pull() { - var buffers = this.buffers || (this.buffers = []); - return buffers.shift(); -} - -function mixinFactory(source) { - return mixin; - - function mixin(target) { - for (var key in source) { - target[key] = source[key]; - } - return target; - } -} - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - -// decode.js - -exports.decode = decode; - -var DecodeBuffer = __webpack_require__(182).DecodeBuffer; - -function decode(input, options) { - var decoder = new DecodeBuffer(options); - decoder.write(input); - return decoder.read(); -} - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - -// decode-buffer.js - -exports.DecodeBuffer = DecodeBuffer; - -var preset = __webpack_require__(183).preset; - -var FlexDecoder = __webpack_require__(180).FlexDecoder; - -FlexDecoder.mixin(DecodeBuffer.prototype); - -function DecodeBuffer(options) { - if (!(this instanceof DecodeBuffer)) return new DecodeBuffer(options); - - if (options) { - this.options = options; - if (options.codec) { - var codec = this.codec = options.codec; - if (codec.bufferish) this.bufferish = codec.bufferish; - } - } -} - -DecodeBuffer.prototype.codec = preset; - -DecodeBuffer.prototype.fetch = function() { - return this.codec.decode(this); -}; - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - -// read-core.js - -var ExtBuffer = __webpack_require__(164).ExtBuffer; -var ExtUnpacker = __webpack_require__(184); -var readUint8 = __webpack_require__(185).readUint8; -var ReadToken = __webpack_require__(186); -var CodecBase = __webpack_require__(179); - -CodecBase.install({ - addExtUnpacker: addExtUnpacker, - getExtUnpacker: getExtUnpacker, - init: init -}); - -exports.preset = init.call(CodecBase.preset); - -function getDecoder(options) { - var readToken = ReadToken.getReadToken(options); - return decode; - - function decode(decoder) { - var type = readUint8(decoder); - var func = readToken[type]; - if (!func) throw new Error("Invalid type: " + (type ? ("0x" + type.toString(16)) : type)); - return func(decoder); - } -} - -function init() { - var options = this.options; - this.decode = getDecoder(options); - - if (options && options.preset) { - ExtUnpacker.setExtUnpackers(this); - } - - return this; -} - -function addExtUnpacker(etype, unpacker) { - var unpackers = this.extUnpackers || (this.extUnpackers = []); - unpackers[etype] = CodecBase.filter(unpacker); -} - -function getExtUnpacker(type) { - var unpackers = this.extUnpackers || (this.extUnpackers = []); - return unpackers[type] || extUnpacker; - - function extUnpacker(buffer) { - return new ExtBuffer(buffer, type); - } -} - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - -// ext-unpacker.js - -exports.setExtUnpackers = setExtUnpackers; - -var Bufferish = __webpack_require__(165); -var Buffer = Bufferish.global; -var _decode; - -var ERROR_COLUMNS = {name: 1, message: 1, stack: 1, columnNumber: 1, fileName: 1, lineNumber: 1}; - -function setExtUnpackers(codec) { - codec.addExtUnpacker(0x0E, [decode, unpackError(Error)]); - codec.addExtUnpacker(0x01, [decode, unpackError(EvalError)]); - codec.addExtUnpacker(0x02, [decode, unpackError(RangeError)]); - codec.addExtUnpacker(0x03, [decode, unpackError(ReferenceError)]); - codec.addExtUnpacker(0x04, [decode, unpackError(SyntaxError)]); - codec.addExtUnpacker(0x05, [decode, unpackError(TypeError)]); - codec.addExtUnpacker(0x06, [decode, unpackError(URIError)]); - - codec.addExtUnpacker(0x0A, [decode, unpackRegExp]); - codec.addExtUnpacker(0x0B, [decode, unpackClass(Boolean)]); - codec.addExtUnpacker(0x0C, [decode, unpackClass(String)]); - codec.addExtUnpacker(0x0D, [decode, unpackClass(Date)]); - codec.addExtUnpacker(0x0F, [decode, unpackClass(Number)]); - - if ("undefined" !== typeof Uint8Array) { - codec.addExtUnpacker(0x11, unpackClass(Int8Array)); - codec.addExtUnpacker(0x12, unpackClass(Uint8Array)); - codec.addExtUnpacker(0x13, [unpackArrayBuffer, unpackClass(Int16Array)]); - codec.addExtUnpacker(0x14, [unpackArrayBuffer, unpackClass(Uint16Array)]); - codec.addExtUnpacker(0x15, [unpackArrayBuffer, unpackClass(Int32Array)]); - codec.addExtUnpacker(0x16, [unpackArrayBuffer, unpackClass(Uint32Array)]); - codec.addExtUnpacker(0x17, [unpackArrayBuffer, unpackClass(Float32Array)]); - - // PhantomJS/1.9.7 doesn't have Float64Array - if ("undefined" !== typeof Float64Array) { - codec.addExtUnpacker(0x18, [unpackArrayBuffer, unpackClass(Float64Array)]); - } - - // IE10 doesn't have Uint8ClampedArray - if ("undefined" !== typeof Uint8ClampedArray) { - codec.addExtUnpacker(0x19, unpackClass(Uint8ClampedArray)); - } - - codec.addExtUnpacker(0x1A, unpackArrayBuffer); - codec.addExtUnpacker(0x1D, [unpackArrayBuffer, unpackClass(DataView)]); - } - - if (Bufferish.hasBuffer) { - codec.addExtUnpacker(0x1B, unpackClass(Buffer)); - } -} - -function decode(input) { - if (!_decode) _decode = __webpack_require__(181).decode; // lazy load - return _decode(input); -} - -function unpackRegExp(value) { - return RegExp.apply(null, value); -} - -function unpackError(Class) { - return function(value) { - var out = new Class(); - for (var key in ERROR_COLUMNS) { - out[key] = value[key]; - } - return out; - }; -} - -function unpackClass(Class) { - return function(value) { - return new Class(value); - }; -} - -function unpackArrayBuffer(value) { - return (new Uint8Array(value)).buffer; -} - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - -// read-format.js - -var ieee754 = __webpack_require__(177); -var Int64Buffer = __webpack_require__(175); -var Uint64BE = Int64Buffer.Uint64BE; -var Int64BE = Int64Buffer.Int64BE; - -exports.getReadFormat = getReadFormat; -exports.readUint8 = uint8; - -var Bufferish = __webpack_require__(165); -var BufferProto = __webpack_require__(171); - -var HAS_MAP = ("undefined" !== typeof Map); -var NO_ASSERT = true; - -function getReadFormat(options) { - var binarraybuffer = Bufferish.hasArrayBuffer && options && options.binarraybuffer; - var int64 = options && options.int64; - var usemap = HAS_MAP && options && options.usemap; - - var readFormat = { - map: (usemap ? map_to_map : map_to_obj), - array: array, - str: str, - bin: (binarraybuffer ? bin_arraybuffer : bin_buffer), - ext: ext, - uint8: uint8, - uint16: uint16, - uint32: uint32, - uint64: read(8, int64 ? readUInt64BE_int64 : readUInt64BE), - int8: int8, - int16: int16, - int32: int32, - int64: read(8, int64 ? readInt64BE_int64 : readInt64BE), - float32: read(4, readFloatBE), - float64: read(8, readDoubleBE) - }; - - return readFormat; -} - -function map_to_obj(decoder, len) { - var value = {}; - var i; - var k = new Array(len); - var v = new Array(len); - - var decode = decoder.codec.decode; - for (i = 0; i < len; i++) { - k[i] = decode(decoder); - v[i] = decode(decoder); - } - for (i = 0; i < len; i++) { - value[k[i]] = v[i]; - } - return value; -} - -function map_to_map(decoder, len) { - var value = new Map(); - var i; - var k = new Array(len); - var v = new Array(len); - - var decode = decoder.codec.decode; - for (i = 0; i < len; i++) { - k[i] = decode(decoder); - v[i] = decode(decoder); - } - for (i = 0; i < len; i++) { - value.set(k[i], v[i]); - } - return value; -} - -function array(decoder, len) { - var value = new Array(len); - var decode = decoder.codec.decode; - for (var i = 0; i < len; i++) { - value[i] = decode(decoder); - } - return value; -} - -function str(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - return BufferProto.toString.call(decoder.buffer, "utf-8", start, end); -} - -function bin_buffer(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return Bufferish.from(buf); -} - -function bin_arraybuffer(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return Bufferish.Uint8Array.from(buf).buffer; -} - -function ext(decoder, len) { - var start = decoder.reserve(len+1); - var type = decoder.buffer[start++]; - var end = start + len; - var unpack = decoder.codec.getExtUnpacker(type); - if (!unpack) throw new Error("Invalid ext type: " + (type ? ("0x" + type.toString(16)) : type)); - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return unpack(buf); -} - -function uint8(decoder) { - var start = decoder.reserve(1); - return decoder.buffer[start]; -} - -function int8(decoder) { - var start = decoder.reserve(1); - var value = decoder.buffer[start]; - return (value & 0x80) ? value - 0x100 : value; -} - -function uint16(decoder) { - var start = decoder.reserve(2); - var buffer = decoder.buffer; - return (buffer[start++] << 8) | buffer[start]; -} - -function int16(decoder) { - var start = decoder.reserve(2); - var buffer = decoder.buffer; - var value = (buffer[start++] << 8) | buffer[start]; - return (value & 0x8000) ? value - 0x10000 : value; -} - -function uint32(decoder) { - var start = decoder.reserve(4); - var buffer = decoder.buffer; - return (buffer[start++] * 16777216) + (buffer[start++] << 16) + (buffer[start++] << 8) + buffer[start]; -} - -function int32(decoder) { - var start = decoder.reserve(4); - var buffer = decoder.buffer; - return (buffer[start++] << 24) | (buffer[start++] << 16) | (buffer[start++] << 8) | buffer[start]; -} - -function read(len, method) { - return function(decoder) { - var start = decoder.reserve(len); - return method.call(decoder.buffer, start, NO_ASSERT); - }; -} - -function readUInt64BE(start) { - return new Uint64BE(this, start).toNumber(); -} - -function readInt64BE(start) { - return new Int64BE(this, start).toNumber(); -} - -function readUInt64BE_int64(start) { - return new Uint64BE(this, start); -} - -function readInt64BE_int64(start) { - return new Int64BE(this, start); -} - -function readFloatBE(start) { - return ieee754.read(this, start, false, 23, 4); -} - -function readDoubleBE(start) { - return ieee754.read(this, start, false, 52, 8); -} - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - -// read-token.js - -var ReadFormat = __webpack_require__(185); - -exports.getReadToken = getReadToken; - -function getReadToken(options) { - var format = ReadFormat.getReadFormat(options); - - if (options && options.useraw) { - return init_useraw(format); - } else { - return init_token(format); - } -} - -function init_token(format) { - var i; - var token = new Array(256); - - // positive fixint -- 0x00 - 0x7f - for (i = 0x00; i <= 0x7f; i++) { - token[i] = constant(i); - } - - // fixmap -- 0x80 - 0x8f - for (i = 0x80; i <= 0x8f; i++) { - token[i] = fix(i - 0x80, format.map); - } - - // fixarray -- 0x90 - 0x9f - for (i = 0x90; i <= 0x9f; i++) { - token[i] = fix(i - 0x90, format.array); - } - - // fixstr -- 0xa0 - 0xbf - for (i = 0xa0; i <= 0xbf; i++) { - token[i] = fix(i - 0xa0, format.str); - } - - // nil -- 0xc0 - token[0xc0] = constant(null); - - // (never used) -- 0xc1 - token[0xc1] = null; - - // false -- 0xc2 - // true -- 0xc3 - token[0xc2] = constant(false); - token[0xc3] = constant(true); - - // bin 8 -- 0xc4 - // bin 16 -- 0xc5 - // bin 32 -- 0xc6 - token[0xc4] = flex(format.uint8, format.bin); - token[0xc5] = flex(format.uint16, format.bin); - token[0xc6] = flex(format.uint32, format.bin); - - // ext 8 -- 0xc7 - // ext 16 -- 0xc8 - // ext 32 -- 0xc9 - token[0xc7] = flex(format.uint8, format.ext); - token[0xc8] = flex(format.uint16, format.ext); - token[0xc9] = flex(format.uint32, format.ext); - - // float 32 -- 0xca - // float 64 -- 0xcb - token[0xca] = format.float32; - token[0xcb] = format.float64; - - // uint 8 -- 0xcc - // uint 16 -- 0xcd - // uint 32 -- 0xce - // uint 64 -- 0xcf - token[0xcc] = format.uint8; - token[0xcd] = format.uint16; - token[0xce] = format.uint32; - token[0xcf] = format.uint64; - - // int 8 -- 0xd0 - // int 16 -- 0xd1 - // int 32 -- 0xd2 - // int 64 -- 0xd3 - token[0xd0] = format.int8; - token[0xd1] = format.int16; - token[0xd2] = format.int32; - token[0xd3] = format.int64; - - // fixext 1 -- 0xd4 - // fixext 2 -- 0xd5 - // fixext 4 -- 0xd6 - // fixext 8 -- 0xd7 - // fixext 16 -- 0xd8 - token[0xd4] = fix(1, format.ext); - token[0xd5] = fix(2, format.ext); - token[0xd6] = fix(4, format.ext); - token[0xd7] = fix(8, format.ext); - token[0xd8] = fix(16, format.ext); - - // str 8 -- 0xd9 - // str 16 -- 0xda - // str 32 -- 0xdb - token[0xd9] = flex(format.uint8, format.str); - token[0xda] = flex(format.uint16, format.str); - token[0xdb] = flex(format.uint32, format.str); - - // array 16 -- 0xdc - // array 32 -- 0xdd - token[0xdc] = flex(format.uint16, format.array); - token[0xdd] = flex(format.uint32, format.array); - - // map 16 -- 0xde - // map 32 -- 0xdf - token[0xde] = flex(format.uint16, format.map); - token[0xdf] = flex(format.uint32, format.map); - - // negative fixint -- 0xe0 - 0xff - for (i = 0xe0; i <= 0xff; i++) { - token[i] = constant(i - 0x100); - } - - return token; -} - -function init_useraw(format) { - var i; - var token = init_token(format).slice(); - - // raw 8 -- 0xd9 - // raw 16 -- 0xda - // raw 32 -- 0xdb - token[0xd9] = token[0xc4]; - token[0xda] = token[0xc5]; - token[0xdb] = token[0xc6]; - - // fixraw -- 0xa0 - 0xbf - for (i = 0xa0; i <= 0xbf; i++) { - token[i] = fix(i - 0xa0, format.bin); - } - - return token; -} - -function constant(value) { - return function() { - return value; - }; -} - -function flex(lenFunc, decodeFunc) { - return function(decoder) { - var len = lenFunc(decoder); - return decodeFunc(decoder, len); - }; -} - -function fix(len, method) { - return function(decoder) { - return method(decoder, len); - }; -} - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - -// encoder.js - -exports.Encoder = Encoder; - -var EventLite = __webpack_require__(188); -var EncodeBuffer = __webpack_require__(162).EncodeBuffer; - -function Encoder(options) { - if (!(this instanceof Encoder)) return new Encoder(options); - EncodeBuffer.call(this, options); -} - -Encoder.prototype = new EncodeBuffer(); - -EventLite.mixin(Encoder.prototype); - -Encoder.prototype.encode = function(chunk) { - this.write(chunk); - this.emit("data", this.read()); -}; - -Encoder.prototype.end = function(chunk) { - if (arguments.length) this.encode(chunk); - this.flush(); - this.emit("end"); -}; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * event-lite.js - Light-weight EventEmitter (less than 1KB when gzipped) - * - * @copyright Yusuke Kawasaki - * @license MIT - * @constructor - * @see https://github.com/kawanet/event-lite - * @see http://kawanet.github.io/event-lite/EventLite.html - * @example - * var EventLite = require("event-lite"); - * - * function MyClass() {...} // your class - * - * EventLite.mixin(MyClass.prototype); // import event methods - * - * var obj = new MyClass(); - * obj.on("foo", function() {...}); // add event listener - * obj.once("bar", function() {...}); // add one-time event listener - * obj.emit("foo"); // dispatch event - * obj.emit("bar"); // dispatch another event - * obj.off("foo"); // remove event listener - */ - -function EventLite() { - if (!(this instanceof EventLite)) return new EventLite(); -} - -(function(EventLite) { - // export the class for node.js - if (true) module.exports = EventLite; - - // property name to hold listeners - var LISTENERS = "listeners"; - - // methods to export - var methods = { - on: on, - once: once, - off: off, - emit: emit - }; - - // mixin to self - mixin(EventLite.prototype); - - // export mixin function - EventLite.mixin = mixin; - - /** - * Import on(), once(), off() and emit() methods into target object. - * - * @function EventLite.mixin - * @param target {Prototype} - */ - - function mixin(target) { - for (var key in methods) { - target[key] = methods[key]; - } - return target; - } - - /** - * Add an event listener. - * - * @function EventLite.prototype.on - * @param type {string} - * @param func {Function} - * @returns {EventLite} Self for method chaining - */ - - function on(type, func) { - getListeners(this, type).push(func); - return this; - } - - /** - * Add one-time event listener. - * - * @function EventLite.prototype.once - * @param type {string} - * @param func {Function} - * @returns {EventLite} Self for method chaining - */ - - function once(type, func) { - var that = this; - wrap.originalListener = func; - getListeners(that, type).push(wrap); - return that; - - function wrap() { - off.call(that, type, wrap); - func.apply(this, arguments); - } - } - - /** - * Remove an event listener. - * - * @function EventLite.prototype.off - * @param [type] {string} - * @param [func] {Function} - * @returns {EventLite} Self for method chaining - */ - - function off(type, func) { - var that = this; - var listners; - if (!arguments.length) { - delete that[LISTENERS]; - } else if (!func) { - listners = that[LISTENERS]; - if (listners) { - delete listners[type]; - if (!Object.keys(listners).length) return off.call(that); - } - } else { - listners = getListeners(that, type, true); - if (listners) { - listners = listners.filter(ne); - if (!listners.length) return off.call(that, type); - that[LISTENERS][type] = listners; - } - } - return that; - - function ne(test) { - return test !== func && test.originalListener !== func; - } - } - - /** - * Dispatch (trigger) an event. - * - * @function EventLite.prototype.emit - * @param type {string} - * @param [value] {*} - * @returns {boolean} True when a listener received the event - */ - - function emit(type, value) { - var that = this; - var listeners = getListeners(that, type, true); - if (!listeners) return false; - var arglen = arguments.length; - if (arglen === 1) { - listeners.forEach(zeroarg); - } else if (arglen === 2) { - listeners.forEach(onearg); - } else { - var args = Array.prototype.slice.call(arguments, 1); - listeners.forEach(moreargs); - } - return !!listeners.length; - - function zeroarg(func) { - func.call(that); - } - - function onearg(func) { - func.call(that, value); - } - - function moreargs(func) { - func.apply(that, args); - } - } - - /** - * @ignore - */ - - function getListeners(that, type, readonly) { - if (readonly && !that[LISTENERS]) return; - var listeners = that[LISTENERS] || (that[LISTENERS] = {}); - return listeners[type] || (listeners[type] = []); - } - -})(EventLite); - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - -// decoder.js - -exports.Decoder = Decoder; - -var EventLite = __webpack_require__(188); -var DecodeBuffer = __webpack_require__(182).DecodeBuffer; - -function Decoder(options) { - if (!(this instanceof Decoder)) return new Decoder(options); - DecodeBuffer.call(this, options); -} - -Decoder.prototype = new DecodeBuffer(); - -EventLite.mixin(Decoder.prototype); - -Decoder.prototype.decode = function(chunk) { - if (arguments.length) this.write(chunk); - this.flush(); -}; - -Decoder.prototype.push = function(chunk) { - this.emit("data", chunk); -}; - -Decoder.prototype.end = function(chunk) { - this.decode(chunk); - this.emit("end"); -}; - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - -// encode-stream.js - -exports.createEncodeStream = EncodeStream; - -var util = __webpack_require__(74); -var Transform = __webpack_require__(106).Transform; -var EncodeBuffer = __webpack_require__(162).EncodeBuffer; - -util.inherits(EncodeStream, Transform); - -var DEFAULT_OPTIONS = {objectMode: true}; - -function EncodeStream(options) { - if (!(this instanceof EncodeStream)) return new EncodeStream(options); - if (options) { - options.objectMode = true; - } else { - options = DEFAULT_OPTIONS; - } - Transform.call(this, options); - - var stream = this; - var encoder = this.encoder = new EncodeBuffer(options); - encoder.push = function(chunk) { - stream.push(chunk); - }; -} - -EncodeStream.prototype._transform = function(chunk, encoding, callback) { - this.encoder.write(chunk); - if (callback) callback(); -}; - -EncodeStream.prototype._flush = function(callback) { - this.encoder.flush(); - if (callback) callback(); -}; - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - -// decode-stream.js - -exports.createDecodeStream = DecodeStream; - -var util = __webpack_require__(74); -var Transform = __webpack_require__(106).Transform; -var DecodeBuffer = __webpack_require__(182).DecodeBuffer; - -util.inherits(DecodeStream, Transform); - -var DEFAULT_OPTIONS = {objectMode: true}; - -function DecodeStream(options) { - if (!(this instanceof DecodeStream)) return new DecodeStream(options); - if (options) { - options.objectMode = true; - } else { - options = DEFAULT_OPTIONS; - } - Transform.call(this, options); - var stream = this; - var decoder = this.decoder = new DecodeBuffer(options); - decoder.push = function(chunk) { - stream.push(chunk); - }; -} - -DecodeStream.prototype._transform = function(chunk, encoding, callback) { - this.decoder.write(chunk); - this.decoder.flush(); - if (callback) callback(); -}; - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - -// ext.js - -// load both interfaces -__webpack_require__(183); -__webpack_require__(163); - -exports.createCodec = __webpack_require__(179).createCodec; - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - -// codec.js - -// load both interfaces -__webpack_require__(183); -__webpack_require__(163); - -// @public -// msgpack.codec.preset - -exports.codec = { - preset: __webpack_require__(179).preset -}; - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(106); -class Buffered extends stream_1.Transform { - constructor() { - super({ - readableHighWaterMark: 10 * 1024 * 1024, - writableHighWaterMark: 10 * 1024 * 1024, - }); - this.chunks = null; - this.timer = null; - } - sendData() { - const { chunks } = this; - if (chunks) { - this.chunks = null; - const buf = Buffer.concat(chunks); - this.push(buf); - } - } - // eslint-disable-next-line consistent-return - _transform(chunk, _encoding, callback) { - const { chunks, timer } = this; - const MIN_SIZE = Buffer.poolSize; - if (timer) - clearTimeout(timer); - if (chunk.length < MIN_SIZE) { - if (!chunks) - return callback(null, chunk); - chunks.push(chunk); - this.sendData(); - callback(); - } - else { - if (!chunks) { - this.chunks = [chunk]; - } - else { - chunks.push(chunk); - } - this.timer = setTimeout(this.sendData.bind(this), 20); - callback(); - } - } - _flush(callback) { - const { chunks } = this; - if (chunks) { - this.chunks = null; - const buf = Buffer.concat(chunks); - callback(null, buf); - } - else { - callback(); - } - } -} -exports.default = Buffered; - - -/***/ }), -/* 195 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Metadata = exports.ExtType = void 0; -const Buffer_1 = __webpack_require__(196); -const Window_1 = __webpack_require__(199); -const Tabpage_1 = __webpack_require__(201); -var ExtType; -(function (ExtType) { - ExtType[ExtType["Buffer"] = 0] = "Buffer"; - ExtType[ExtType["Window"] = 1] = "Window"; - ExtType[ExtType["Tabpage"] = 2] = "Tabpage"; -})(ExtType = exports.ExtType || (exports.ExtType = {})); -exports.Metadata = [ - { - constructor: Buffer_1.Buffer, - name: 'Buffer', - prefix: 'nvim_buf_', - }, - { - constructor: Window_1.Window, - name: 'Window', - prefix: 'nvim_win_', - }, - { - constructor: Tabpage_1.Tabpage, - name: 'Tabpage', - prefix: 'nvim_tabpage_', - }, -]; - - -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Buffer = void 0; -const Base_1 = __webpack_require__(197); -class Buffer extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = 'nvim_buf_'; - } - /** - * Attach to buffer to listen to buffer events - * @param sendBuffer Set to true if the initial notification should contain - * the whole buffer. If so, the first notification will be a - * `nvim_buf_lines_event`. Otherwise, the first notification will be - * a `nvim_buf_changedtick_event` - */ - async attach(sendBuffer = false, options = {}) { - return await this.request(`${this.prefix}attach`, [sendBuffer, options]); - } - /** - * Detach from buffer to stop listening to buffer events - */ - async detach() { - return await this.request(`${this.prefix}detach`, []); - } - /** - * Get the bufnr of Buffer - */ - get id() { - return this.data; - } - /** Total number of lines in buffer */ - get length() { - return this.request(`${this.prefix}line_count`, []); - } - /** Get lines in buffer */ - get lines() { - return this.getLines(); - } - /** Gets a changed tick of a buffer */ - get changedtick() { - return this.request(`${this.prefix}get_changedtick`, []); - } - get commands() { - return this.getCommands(); - } - getCommands(options = {}) { - return this.request(`${this.prefix}get_commands`, [options]); - } - /** Get specific lines of buffer */ - getLines({ start, end, strictIndexing } = { start: 0, end: -1, strictIndexing: true }) { - const indexing = typeof strictIndexing === 'undefined' ? true : strictIndexing; - return this.request(`${this.prefix}get_lines`, [ - start, - end, - indexing, - ]); - } - /** Set lines of buffer given indeces */ - setLines(_lines, { start: _start, end: _end, strictIndexing } = { - strictIndexing: true, - }, notify = false) { - // TODO: Error checking - // if (typeof start === 'undefined' || typeof end === 'undefined') { - // } - const indexing = typeof strictIndexing === 'undefined' ? true : strictIndexing; - const lines = typeof _lines === 'string' ? [_lines] : _lines; - const end = typeof _end !== 'undefined' ? _end : _start + 1; - const method = notify ? 'notify' : 'request'; - return this[method](`${this.prefix}set_lines`, [ - _start, - end, - indexing, - lines, - ]); - } - /** - * Set virtual text for a line - * - * @public - * @param {number} src_id - Source group to use or 0 to use a new group, or -1 - * @param {number} line - Line to annotate with virtual text (zero-indexed) - * @param {Chunk[]} chunks - List with [text, hl_group] - * @param {{[index} opts - * @returns {Promise} - */ - setVirtualText(src_id, line, chunks, opts = {}) { - this.notify(`${this.prefix}set_virtual_text`, [ - src_id, - line, - chunks, - opts, - ]); - return Promise.resolve(src_id); - } - /** Insert lines at `start` index */ - insert(lines, start) { - return this.setLines(lines, { - start, - end: start, - strictIndexing: true, - }); - } - /** Replace lines starting at `start` index */ - replace(_lines, start) { - const lines = typeof _lines === 'string' ? [_lines] : _lines; - return this.setLines(lines, { - start, - end: start + lines.length, - strictIndexing: false, - }); - } - /** Remove lines at index */ - remove(start, end, strictIndexing = false) { - return this.setLines([], { start, end, strictIndexing }); - } - /** Append a string or list of lines to end of buffer */ - append(lines) { - return this.setLines(lines, { - start: -1, - end: -1, - strictIndexing: false, - }); - } - /** Get buffer name */ - get name() { - return this.request(`${this.prefix}get_name`, []); - } - /** Set current buffer name */ - setName(value) { - return this.request(`${this.prefix}set_name`, [value]); - } - /** Is current buffer valid */ - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - /** Get mark position given mark name */ - mark(name) { - return this.request(`${this.prefix}get_mark`, [name]); - } - // range(start, end) { - // """Return a `Range` object, which represents part of the Buffer.""" - // return Range(this, start, end) - // } - /** Gets keymap */ - getKeymap(mode) { - return this.request(`${this.prefix}get_keymap`, [mode]); - } - /** - * Checks if a buffer is valid and loaded. See |api-buffer| for - * more info about unloaded buffers. - */ - get loaded() { - return this.request(`${this.prefix}is_loaded`, []); - } - /** - * Returns the byte offset for a line. - * - * Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is - * one byte. 'fileformat' and 'fileencoding' are ignored. The - * line index just after the last line gives the total byte-count - * of the buffer. A final EOL byte is counted if it would be - * written, see 'eol'. - * - * Unlike |line2byte()|, throws error for out-of-bounds indexing. - * Returns -1 for unloaded buffer. - * - * @return {Number} Integer byte offset, or -1 for unloaded buffer. - */ - getOffset(index) { - return this.request(`${this.prefix}get_offset`, [index]); - } - /** - Adds a highlight to buffer. - - This can be used for plugins which dynamically generate - highlights to a buffer (like a semantic highlighter or - linter). The function adds a single highlight to a buffer. - Unlike matchaddpos() highlights follow changes to line - numbering (as lines are inserted/removed above the highlighted - line), like signs and marks do. - - "src_id" is useful for batch deletion/updating of a set of - highlights. When called with src_id = 0, an unique source id - is generated and returned. Succesive calls can pass in it as - "src_id" to add new highlights to the same source group. All - highlights in the same group can then be cleared with - nvim_buf_clear_highlight. If the highlight never will be - manually deleted pass in -1 for "src_id". - - If "hl_group" is the empty string no highlight is added, but a - new src_id is still returned. This is useful for an external - plugin to synchrounously request an unique src_id at - initialization, and later asynchronously add and clear - highlights in response to buffer changes. */ - addHighlight({ hlGroup: _hlGroup, line, colStart: _start, colEnd: _end, srcId: _srcId, }) { - const hlGroup = typeof _hlGroup !== 'undefined' ? _hlGroup : ''; - const colEnd = typeof _end !== 'undefined' ? _end : -1; - const colStart = typeof _start !== 'undefined' ? _start : -0; - const srcId = typeof _srcId !== 'undefined' ? _srcId : -1; - const method = srcId == -1 ? 'request' : 'notify'; - let res = this[method](`${this.prefix}add_highlight`, [ - srcId, - hlGroup, - line, - colStart, - colEnd, - ]); - return method === 'request' ? res : Promise.resolve(null); - } - /** Clears highlights from a given source group and a range of - lines - To clear a source group in the entire buffer, pass in 1 and -1 - to lineStart and lineEnd respectively. */ - clearHighlight(args = {}) { - const defaults = { - srcId: -1, - lineStart: 0, - lineEnd: -1, - }; - const { srcId, lineStart, lineEnd } = Object.assign({}, defaults, args); - return this.notify(`${this.prefix}clear_highlight`, [ - srcId, - lineStart, - lineEnd, - ]); - } - clearNamespace(id, lineStart = 0, lineEnd = -1) { - return this.notify(`${this.prefix}clear_namespace`, [ - id, - lineStart, - lineEnd, - ]); - } - /** - * Listens to buffer for events - */ - listen(eventName, cb, disposables) { - this.client.attachBufferEvent(this, eventName, cb); - if (disposables) { - disposables.push({ - dispose: () => { - this.client.detachBufferEvent(this, eventName, cb); - } - }); - } - } -} -exports.Buffer = Buffer; - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseApi = void 0; -const events_1 = __webpack_require__(198); -const isVim = process.env.VIM_NODE_RPC == '1'; -// i.e. a plugin that detaches will affect all plugins registered on host -// const EXCLUDED = ['nvim_buf_attach', 'nvim_buf_detach'] -// Instead of dealing with multiple inheritance (or lackof), just extend EE -// Only the Neovim API class should use EE though -class BaseApi extends events_1.EventEmitter { - constructor({ transport, data, client, }) { - super(); - this.setTransport(transport); - this.data = data; - this.client = client; - } - setTransport(transport) { - this.transport = transport; - } - equals(other) { - try { - return String(this.data) === String(other.data); - } - catch (e) { - return false; - } - } - async request(name, args = []) { - let stack = Error().stack; - return new Promise((resolve, reject) => { - this.transport.request(name, this.getArgsByPrefix(args), (err, res) => { - if (err) { - let e = new Error(`request error ${name} - ${err[1]}`); - e.stack = stack; - if (!name.endsWith('get_var')) { - this.client.logError(`request error on "${name}"`, args, err[1], stack); - } - reject(e); - } - else { - resolve(res); - } - }); - }); - } - getArgsByPrefix(args) { - // Check if class is Neovim and if so, should not send `this` as first arg - if (this.prefix !== 'nvim_' && args[0] != this) { - let id = isVim ? this.data : this; - return [id, ...args]; - } - return args; - } - /** Retrieves a scoped variable depending on type (using `this.prefix`) */ - getVar(name) { - return this.request(`${this.prefix}get_var`, [name]).then(res => res, _err => { - return null; - }); - } - setVar(name, value, isNotify = false) { - if (isNotify) { - this.notify(`${this.prefix}set_var`, [name, value]); - return; - } - return this.request(`${this.prefix}set_var`, [name, value]); - } - /** Delete a scoped variable */ - deleteVar(name) { - this.notify(`${this.prefix}del_var`, [name]); - } - /** Retrieves a scoped option depending on type of `this` */ - getOption(name) { - return this.request(`${this.prefix}get_option`, [name]); - } - setOption(name, value, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}set_option`, [name, value]); - return; - } - return this.request(`${this.prefix}set_option`, [name, value]); - } - /** `request` is basically the same except you can choose to wait forpromise to be resolved */ - notify(name, args = []) { - this.transport.notify(name, this.getArgsByPrefix(args)); - } -} -exports.BaseApi = BaseApi; - - -/***/ }), -/* 198 */ -/***/ (function(module, exports) { - -module.exports = require("events"); - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Window = void 0; -const Base_1 = __webpack_require__(197); -const timers_1 = __webpack_require__(200); -class Window extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = 'nvim_win_'; - } - /** - * The windowid that not change within a Vim session - */ - get id() { - return this.data; - } - /** Get current buffer of window */ - get buffer() { - return this.request(`${this.prefix}get_buf`, []); - } - /** Get the Tabpage that contains the window */ - get tabpage() { - return this.request(`${this.prefix}get_tabpage`, []); - } - /** Get cursor position */ - get cursor() { - return this.request(`${this.prefix}get_cursor`, []); - } - setCursor(pos, isNotify = false) { - let method = isNotify ? 'notify' : 'request'; - return this[method](`${this.prefix}set_cursor`, [pos]); - } - /** Get window height by number of rows */ - get height() { - return this.request(`${this.prefix}get_height`, []); - } - setHeight(height, isNotify = false) { - let method = isNotify ? 'notify' : 'request'; - return this[method](`${this.prefix}set_height`, [height]); - } - /** Get window width by number of columns */ - get width() { - return this.request(`${this.prefix}get_width`, []); - } - setWidth(width, isNotify = false) { - let method = isNotify ? 'notify' : 'request'; - return this[method](`${this.prefix}set_height`, [width]); - } - /** Get window position */ - get position() { - return this.request(`${this.prefix}get_position`, []); - } - /** 0-indexed, on-screen window position(row) in display cells. */ - get row() { - return this.request(`${this.prefix}get_position`, []).then(position => position[0]); - } - /** 0-indexed, on-screen window position(col) in display cells. */ - get col() { - return this.request(`${this.prefix}get_position`, []).then(position => position[1]); - } - /** Is window valid */ - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - /** Get window number */ - get number() { - return this.request(`${this.prefix}get_number`, []); - } - setConfig(options, isNotify) { - let method = isNotify ? 'notify' : 'request'; - return this[method](`${this.prefix}set_config`, [options]); - } - getConfig() { - return this.request(`${this.prefix}get_config`, []); - } - close(force, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}close`, [force]); - let count = 0; - let interval = setInterval(() => { - if (count == 5) - return timers_1.clearInterval(interval); - this.request(`${this.prefix}is_valid`, []).then(valid => { - if (!valid) { - timers_1.clearInterval(interval); - } - else { - this.notify(`${this.prefix}close`, [force]); - } - }, () => { - timers_1.clearInterval(interval); - }); - count++; - }, 50); - return null; - } - return this.request(`${this.prefix}close`, [force]); - } -} -exports.Window = Window; - - -/***/ }), -/* 200 */ -/***/ (function(module, exports) { - -module.exports = require("timers"); - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Tabpage = void 0; -const Base_1 = __webpack_require__(197); -class Tabpage extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = 'nvim_tabpage_'; - } - /** Returns all windows of tabpage */ - get windows() { - return this.request(`${this.prefix}list_wins`, []); - } - /** Gets the current window of tabpage */ - get window() { - return this.request(`${this.prefix}get_win`, []); - } - /** Is current tabpage valid */ - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - /** Tabpage number */ - get number() { - return this.request(`${this.prefix}get_number`, []); - } - /** Invalid */ - getOption() { - throw new Error('Tabpage does not have `getOption`'); - } - /** Invalid */ - setOption() { - throw new Error('Tabpage does not have `setOption`'); - } -} -exports.Tabpage = Tabpage; - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(198); -const logger_1 = __webpack_require__(203); -const debug = process.env.NODE_CLIENT_LOG_LEVEL == 'debug'; -const logger = logger_1.createLogger('transport'); -class Transport extends events_1.EventEmitter { - constructor(logger) { - super(); - this.logger = logger; - this.pauseLevel = 0; - this.paused = new Map(); - } - debug(key, ...meta) { - if (!debug) - return; - logger.debug(key, ...meta); - } - info(key, ...meta) { - logger.info(key, ...meta); - } - debugMessage(msg) { - if (!debug) - return; - const msgType = msg[0]; - if (msgType == 0) { - logger.debug('receive request:', msg.slice(1)); - } - else if (msgType == 1) { - // logger.debug('receive response:', msg.slice(1)) - } - else if (msgType == 2) { - logger.debug('receive notification:', msg.slice(1)); - } - else { - logger.debug('unknown message:', msg); - } - } - pauseNotification() { - this.pauseLevel = this.pauseLevel + 1; - this.paused.set(this.pauseLevel, []); - } - cancelNotification() { - let { pauseLevel } = this; - if (pauseLevel > 0) { - this.paused.delete(pauseLevel); - this.pauseLevel = pauseLevel - 1; - } - } - resumeNotification(isNotify = false) { - let { pauseLevel } = this; - if (pauseLevel == 0) - return isNotify ? null : Promise.resolve([null, null]); - let stack = Error().stack; - this.pauseLevel = pauseLevel - 1; - let list = this.paused.get(pauseLevel); - this.paused.delete(pauseLevel); - if (list && list.length) { - return new Promise((resolve, reject) => { - if (!isNotify) { - return this.request('nvim_call_atomic', [list], (err, res) => { - if (err) { - let e = new Error(`call_atomic error: ${err[1]}`); - e.stack = stack; - return reject(e); - } - if (Array.isArray(res) && res[1] != null) { - let [index, errType, message] = res[1]; - let [fname, args] = list[index]; - this.logger.error(`request error ${errType} on "${fname}"`, args, message, stack); - } - resolve(res); - }); - } - this.notify('nvim_call_atomic', [list]); - resolve(); - }); - } - return isNotify ? null : Promise.resolve([[], undefined]); - } -} -exports.default = Transport; - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createLogger = void 0; -const fs_1 = __importDefault(__webpack_require__(66)); -const os_1 = __importDefault(__webpack_require__(76)); -const path_1 = __importDefault(__webpack_require__(82)); -function getLogFile() { - let file = process.env.NODE_CLIENT_LOG_FILE; - if (file) - return file; - let dir = process.env.XDG_RUNTIME_DIR; - if (dir) - return path_1.default.join(dir, 'node-client.log'); - return path_1.default.join(os_1.default.tmpdir(), `node-client-${process.pid}.log`); -} -const LOG_FILE_PATH = getLogFile(); -const level = process.env.NODE_CLIENT_LOG_LEVEL || 'info'; -let invalid = process.getuid && process.getuid() == 0; -if (!invalid) { - try { - fs_1.default.mkdirSync(path_1.default.dirname(LOG_FILE_PATH), { recursive: true }); - fs_1.default.writeFileSync(LOG_FILE_PATH, '', { encoding: 'utf8', mode: 0o666 }); - } - catch (_e) { - invalid = true; - } -} -function toObject(arg) { - if (arg == null) { - return arg; - } - if (Array.isArray(arg)) { - return arg.map(o => toObject(o)); - } - if (typeof arg == 'object' && typeof arg.prefix == 'string' && typeof arg.data == 'number') { - return '[' + arg.prefix + arg.data + ']'; - } - return arg; -} -function toString(arg) { - if (arg == null) - return String(arg); - if (typeof arg == 'object') - return JSON.stringify(arg, null, 2); - return String(arg); -} -class Logger { - constructor(name) { - this.name = name; - } - get stream() { - if (invalid) - return null; - if (this._stream) - return this._stream; - this._stream = fs_1.default.createWriteStream(LOG_FILE_PATH, { encoding: 'utf8' }); - return this._stream; - } - getText(level, data, meta) { - let more = ''; - if (meta.length) { - let arr = toObject(meta); - more = ' ' + arr.map(o => toString(o)); - } - return `${new Date().toLocaleTimeString()} ${level.toUpperCase()} [${this.name}] - ${data}${more}\n`; - } - debug(data, ...meta) { - if (level != 'debug' || this.stream == null) - return; - this.stream.write(this.getText('debug', data, meta)); - } - info(data, ...meta) { - if (this.stream == null) - return; - this.stream.write(this.getText('info', data, meta)); - } - error(data, ...meta) { - if (this.stream == null) - return; - this.stream.write(this.getText('error', data, meta)); - } - trace(data, ...meta) { - if (level != 'trace' || this.stream == null) - return; - this.stream.write(this.getText('trace', data, meta)); - } -} -function createLogger(name) { - return new Logger(name); -} -exports.createLogger = createLogger; - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VimTransport = void 0; -const base_1 = __importDefault(__webpack_require__(202)); -const connection_1 = __importDefault(__webpack_require__(205)); -const request_1 = __importDefault(__webpack_require__(207)); -class VimTransport extends base_1.default { - constructor(logger) { - super(logger); - this.pending = new Map(); - this.nextRequestId = -1; - this.attached = false; - this.notifyMethod = process.env.COC_NVIM == '1' ? 'coc#api#notify' : 'nvim#api#notify'; - } - attach(writer, reader, client) { - let connection = this.connection = new connection_1.default(reader, writer); - this.attached = true; - this.client = client; - connection.on('request', (id, obj) => { - let [method, args] = obj; - this.emit('request', method, args, this.createResponse(id)); - }); - connection.on('notification', (obj) => { - let [event, args] = obj; - this.emit('notification', event.toString(), args); - }); - connection.on('response', (id, obj) => { - let req = this.pending.get(id); - if (req) { - this.pending.delete(id); - let err = null; - let result = null; - if (!Array.isArray(obj)) { - err = obj; - } - else { - err = obj[0]; - result = obj[1]; - } - req.callback(this.client, err, result); - } - }); - } - send(arr) { - this.connection.send(arr); - } - detach() { - if (!this.attached) - return; - this.attached = false; - this.connection.dispose(); - } - /** - * Send request to vim - */ - request(method, args, cb) { - if (!this.attached) - return cb([0, 'transport disconnected']); - let id = this.nextRequestId; - this.nextRequestId = this.nextRequestId - 1; - let startTs = Date.now(); - this.debug('request to vim:', id, method, args); - let timer = setTimeout(() => { - this.debug(`request to vim cost more than 1s`, method, args); - }, 1000); - let req = new request_1.default(this.connection, (err, res) => { - clearTimeout(timer); - this.debug(`response from vim cost:`, id, `${Date.now() - startTs}ms`); - cb(err, res); - }, id); - this.pending.set(id, req); - req.request(method, args); - } - notify(method, args) { - if (!this.attached) - return; - if (this.pauseLevel != 0) { - let arr = this.paused.get(this.pauseLevel); - if (arr) { - arr.push([method, args]); - return; - } - } - this.connection.call(this.notifyMethod, [method.slice(5), args]); - } - createResponse(requestId) { - let called = false; - let { connection } = this; - let startTs = Date.now(); - let timer = setTimeout(() => { - this.debug(`request to client cost more than 1s`, requestId); - }, 1000); - return { - send: (resp, isError) => { - clearTimeout(timer); - if (called || !this.attached) - return; - called = true; - let err = null; - if (isError) - err = typeof resp === 'string' ? resp : resp.toString(); - this.debug('response of client cost:', requestId, `${Date.now() - startTs}ms`); - connection.response(requestId, [err, isError ? null : resp]); - } - }; - } -} -exports.VimTransport = VimTransport; - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __importDefault(__webpack_require__(198)); -const readline_1 = __importDefault(__webpack_require__(206)); -const logger_1 = __webpack_require__(203); -const logger = logger_1.createLogger('connection'); -const debug = process.env.NODE_CLIENT_LOG_LEVEL == 'debug'; -class Connection extends events_1.default { - constructor(readable, writeable) { - super(); - this.readable = readable; - this.writeable = writeable; - const rl = readline_1.default.createInterface(this.readable); - rl.on('line', (line) => { - this.parseData(line); - }); - rl.on('close', () => { - logger.error('connection closed'); - process.exit(0); - }); - } - parseData(str) { - if (str.length == 0) - return; - let arr; - try { - arr = JSON.parse(str); - } - catch (e) { - // tslint:disable-next-line: no-console - console.error(`Invalid data from vim: ${str}`); - return; - } - // request, notification, response - let [id, obj] = arr; - if (id > 0) { - logger.debug('received request:', id, obj); - this.emit('request', id, obj); - } - else if (id == 0) { - logger.debug('received notification:', obj); - this.emit('notification', obj); - } - else { - logger.debug('received response:', id, obj); - // response for previous request - this.emit('response', id, obj); - } - } - response(requestId, data) { - this.send([requestId, data || null]); - } - notify(event, data) { - this.send([0, [event, data || null]]); - } - send(arr) { - logger.debug('send to vim:', arr); - try { - this.writeable.write(JSON.stringify(arr) + '\n'); - } - catch (e) { - logger.error('Send error:', arr); - } - } - redraw(force = false) { - this.send(['redraw', force ? 'force' : '']); - } - commmand(cmd) { - this.send(['ex', cmd]); - } - expr(expr) { - this.send(['expr', expr]); - } - call(func, args, requestId) { - if (!requestId) { - this.send(['call', func, args]); - return; - } - this.send(['call', func, args, requestId]); - } - dispose() { - this.removeAllListeners(); - } -} -exports.default = Connection; - - -/***/ }), -/* 206 */ -/***/ (function(module, exports) { - -module.exports = require("readline"); - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const logger_1 = __webpack_require__(203); -const logger = logger_1.createLogger('request'); -const debug = process.env.NODE_CLIENT_LOG_LEVEL == 'debug'; -const func = process.env.COC_NVIM == '1' ? 'coc#api#call' : 'nvim#api#call'; -class Request { - constructor(connection, cb, id) { - this.connection = connection; - this.cb = cb; - this.id = id; - } - request(method, args = []) { - this.method = method; - this.args = args; - this.connection.call(func, [method.slice(5), args], this.id); - } - callback(client, err, result) { - let { method, cb } = this; - if (debug && err) { - logger.debug(`request ${this.method} error:`, err, this.args); - } - if (err) - return cb([0, err.toString()]); - switch (method) { - case 'nvim_list_wins': - case 'nvim_tabpage_list_wins': - return cb(null, result.map(o => client.createWindow(o))); - case 'nvim_tabpage_get_win': - case 'nvim_get_current_win': - case 'nvim_open_win': - return cb(null, client.createWindow(result)); - case 'nvim_list_bufs': - return cb(null, result.map(o => client.createBuffer(o))); - case 'nvim_win_get_buf': - case 'nvim_create_buf': - case 'nvim_get_current_buf': - return cb(null, client.createBuffer(result)); - case 'nvim_list_tabpages': - return cb(null, result.map(o => client.createTabpage(o))); - case 'nvim_get_current_tabpage': - return cb(null, client.createTabpage(result)); - default: - return cb(null, result); - } - } -} -exports.default = Request; - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Neovim = void 0; -const Base_1 = __webpack_require__(197); -const Buffer_1 = __webpack_require__(196); -const Tabpage_1 = __webpack_require__(201); -const Window_1 = __webpack_require__(199); -const isVim = process.env.VIM_NODE_RPC == '1'; -/** - * Neovim API - */ -class Neovim extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = 'nvim_'; - this.Buffer = Buffer_1.Buffer; - this.Window = Window_1.Window; - this.Tabpage = Tabpage_1.Tabpage; - } - getArgs(args) { - if (!args) - return []; - if (Array.isArray(args)) - return args; - return [args]; - } - get apiInfo() { - return this.request(`${this.prefix}get_api_info`); - } - /** Get list of all buffers */ - get buffers() { - return this.request(`${this.prefix}list_bufs`); - } - /** Get current buffer */ - get buffer() { - return this.request(`${this.prefix}get_current_buf`); - } - /** Set current buffer */ - async setBuffer(buffer) { - await this.request(`${this.prefix}set_current_buf`, [buffer]); - } - get chans() { - return this.request(`${this.prefix}list_chans`); - } - getChanInfo(chan) { - return this.request(`${this.prefix}get_chan_info`, [chan]); - } - createNamespace(name = "") { - return this.request(`${this.prefix}create_namespace`, [name]); - } - get namespaces() { - return this.request(`${this.prefix}get_namespaces`, []); - } - get commands() { - return this.getCommands(); - } - getCommands(options = {}) { - return this.request(`${this.prefix}get_commands`, [options]); - } - /** Get list of all tabpages */ - get tabpages() { - return this.request(`${this.prefix}list_tabpages`); - } - /** Get current tabpage */ - get tabpage() { - return this.request(`${this.prefix}get_current_tabpage`); - } - /** Set current tabpage */ - async setTabpage(tabpage) { - await this.request(`${this.prefix}set_current_tabpage`, [tabpage]); - } - /** Get list of all windows */ - get windows() { - return this.getWindows(); - } - /** Get current window */ - get window() { - return this.request(`${this.prefix}get_current_win`); - } - /** Get list of all windows */ - getWindows() { - return this.request(`${this.prefix}list_wins`); - } - async setWindow(win) { - // Throw error if win is not instance of Window? - await this.request(`${this.prefix}set_current_win`, [win]); - } - /** Get list of all runtime paths */ - get runtimePaths() { - return this.request(`${this.prefix}list_runtime_paths`); - } - /** Set current directory */ - setDirectory(dir) { - return this.request(`${this.prefix}set_current_dir`, [dir]); - } - /** Get current line. Always returns a Promise. */ - get line() { - return this.getLine(); - } - createNewBuffer(listed = false, scratch = false) { - return this.request(`${this.prefix}create_buf`, [listed, scratch]); - } - openFloatWindow(buffer, enter, options) { - return this.request(`${this.prefix}open_win`, [buffer, enter, options]); - } - getLine() { - return this.request(`${this.prefix}get_current_line`); - } - /** Set current line */ - setLine(line) { - return this.request(`${this.prefix}set_current_line`, [line]); - } - /** Gets keymap */ - getKeymap(mode) { - return this.request(`${this.prefix}get_keymap`, [mode]); - } - /** Gets current mode */ - get mode() { - return this.request(`${this.prefix}get_mode`); - } - /** Gets map of defined colors */ - get colorMap() { - return this.request(`${this.prefix}get_color_map`); - } - /** Get color by name */ - getColorByName(name) { - return this.request(`${this.prefix}get_color_by_name`, [name]); - } - /** Get highlight by name or id */ - getHighlight(nameOrId, isRgb = true) { - const functionName = typeof nameOrId === 'string' ? 'by_name' : 'by_id'; - return this.request(`${this.prefix}get_hl_${functionName}`, [ - nameOrId, - isRgb, - ]); - } - getHighlightByName(name, isRgb = true) { - return this.request(`${this.prefix}get_hl_by_name`, [name, isRgb]); - } - getHighlightById(id, isRgb = true) { - return this.request(`${this.prefix}get_hl_by_id`, [id, isRgb]); - } - /** Delete current line in buffer */ - deleteCurrentLine() { - return this.request(`${this.prefix}del_current_line`); - } - /** - * Evaluates a VimL expression (:help expression). Dictionaries - * and Lists are recursively expanded. On VimL error: Returns a - * generic error; v:errmsg is not updated. - * - */ - eval(expr) { - return this.request(`${this.prefix}eval`, [expr]); - } - /** - * Executes lua, it's possible neovim client does not support this - */ - lua(code, args = []) { - const _args = this.getArgs(args); - return this.request(`${this.prefix}execute_lua`, [code, _args]); - } - // Alias for `lua()` to be consistent with neovim API - executeLua(code, args = []) { - return this.lua(code, args); - } - callDictFunction(dict, fname, args = []) { - const _args = this.getArgs(args); - return this.request(`${this.prefix}call_dict_function`, [ - dict, - fname, - _args, - ]); - } - call(fname, args = [], isNotify) { - const _args = this.getArgs(args); - if (isNotify) { - this.notify(`${this.prefix}call_function`, [fname, _args]); - return null; - } - return this.request(`${this.prefix}call_function`, [fname, _args]); - } - callTimer(fname, args = [], isNotify) { - const _args = this.getArgs(args); - if (isNotify) { - this.notify(`${this.prefix}call_function`, ['coc#util#timer', [fname, _args]]); - return null; - } - if (isVim) { - this.notify(`${this.prefix}call_function`, ['coc#util#timer', [fname, _args]]); - return new Promise(resolve => { - setTimeout(() => { - resolve(null); - }, 20); - }); - } - return this.request(`${this.prefix}call_function`, ['coc#util#timer', [fname, _args]]); - } - callAsync(fname, args = []) { - const _args = this.getArgs(args); - return this.client.sendAsyncRequest(fname, _args); - } - /** Alias for `call` */ - callFunction(fname, args = []) { - return this.call(fname, args); - } - /** Call Atomic calls */ - callAtomic(calls) { - return this.request(`${this.prefix}call_atomic`, [calls]); - } - command(arg, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}command`, [arg]); - return null; - } - return this.request(`${this.prefix}command`, [arg]); - } - /** Runs a command and returns output (synchronous?) */ - commandOutput(arg) { - return this.request(`${this.prefix}command_output`, [arg]); - } - /** Gets a v: variable */ - getVvar(name) { - return this.request(`${this.prefix}get_vvar`, [name]); - } - /** feedKeys */ - feedKeys(keys, mode, escapeCsi) { - return this.request(`${this.prefix}feedkeys`, [keys, mode, escapeCsi]); - } - /** Sends input keys */ - input(keys) { - return this.request(`${this.prefix}input`, [keys]); - } - /** - * Parse a VimL Expression - * - * TODO: return type, see :help - */ - parseExpression(expr, flags, highlight) { - return this.request(`${this.prefix}parse_expression`, [ - expr, - flags, - highlight, - ]); - } - getProc(pid) { - return this.request(`${this.prefix}get_proc`, [pid]); - } - getProcChildren(pid) { - return this.request(`${this.prefix}get_proc_children`, [pid]); - } - /** Replace term codes */ - replaceTermcodes(str, fromPart, doIt, special) { - return this.request(`${this.prefix}replace_termcodes`, [ - str, - fromPart, - doIt, - special, - ]); - } - /** Gets width of string */ - strWidth(str) { - return this.request(`${this.prefix}strwidth`, [str]); - } - /** Write to output buffer */ - outWrite(str) { - this.notify(`${this.prefix}out_write`, [str]); - } - outWriteLine(str) { - this.outWrite(`${str}\n`); - } - /** Write to error buffer */ - errWrite(str) { - this.notify(`${this.prefix}err_write`, [str]); - } - /** Write to error buffer */ - errWriteLine(str) { - this.notify(`${this.prefix}err_writeln`, [str]); - } - // TODO: add type - get uis() { - return this.request(`${this.prefix}list_uis`); - } - uiAttach(width, height, options) { - return this.request(`${this.prefix}ui_attach`, [width, height, options]); - } - uiDetach() { - return this.request(`${this.prefix}ui_detach`, []); - } - uiTryResize(width, height) { - return this.request(`${this.prefix}ui_try_resize`, [width, height]); - } - /** Set UI Option */ - uiSetOption(name, value) { - return this.request(`${this.prefix}ui_set_option`, [name, value]); - } - /** Subscribe to nvim event broadcasts */ - subscribe(event) { - return this.request(`${this.prefix}subscribe`, [event]); - } - /** Unsubscribe to nvim event broadcasts */ - unsubscribe(event) { - return this.request(`${this.prefix}unsubscribe`, [event]); - } - setClientInfo(name, version, type, methods, attributes) { - this.notify(`${this.prefix}set_client_info`, [ - name, - version, - type, - methods, - attributes, - ]); - } - /** Quit nvim */ - async quit() { - this.command('qa!', true); - if (this.transport) { - this.transport.detach(); - } - } -} -exports.Neovim = Neovim; - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Tabpage = exports.Window = exports.Buffer = exports.NeovimClient = exports.Neovim = void 0; -var client_1 = __webpack_require__(158); -Object.defineProperty(exports, "Neovim", { enumerable: true, get: function () { return client_1.NeovimClient; } }); -var client_2 = __webpack_require__(158); -Object.defineProperty(exports, "NeovimClient", { enumerable: true, get: function () { return client_2.NeovimClient; } }); -var Buffer_1 = __webpack_require__(196); -Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return Buffer_1.Buffer; } }); -var Window_1 = __webpack_require__(199); -Object.defineProperty(exports, "Window", { enumerable: true, get: function () { return Window_1.Window; } }); -var Tabpage_1 = __webpack_require__(201); -Object.defineProperty(exports, "Tabpage", { enumerable: true, get: function () { return Tabpage_1.Tabpage; } }); - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const util_1 = __webpack_require__(238); -const object_1 = __webpack_require__(249); -const logger = __webpack_require__(64)('events'); -class Events { - constructor() { - this.handlers = new Map(); - this.insertMode = false; - } - get cursor() { - return this._cursor; - } - async fire(event, args) { - logger.debug('Event:', event, args); - let cbs = this.handlers.get(event); - if (event == 'InsertEnter') { - this.insertMode = true; - } - else if (event == 'InsertLeave') { - this.insertMode = false; - } - else if (!this.insertMode && (event == 'CursorHoldI' || event == 'CursorMovedI')) { - this.insertMode = true; - await this.fire('InsertEnter', [args[0]]); - } - else if (this.insertMode && (event == 'CursorHold' || event == 'CursorMoved')) { - this.insertMode = false; - await this.fire('InsertLeave', [args[0]]); - } - if (event == 'CursorMoved' || event == 'CursorMovedI') { - let cursor = { - bufnr: args[0], - lnum: args[1][0], - col: args[1][1], - insert: event == 'CursorMovedI' - }; - // not handle CursorMoved when it's not moved at all - if (this._cursor && object_1.equals(this._cursor, cursor)) - return; - this._cursor = cursor; - } - if (cbs) { - try { - await Promise.all(cbs.map(fn => fn(args))); - } - catch (e) { - if (e.message && e.message.indexOf('transport disconnected') == -1) { - console.error(`Error on ${event}: ${e.message}${e.stack ? '\n' + e.stack : ''} `); - } - logger.error(`Handler Error on ${event}`, e.stack); - } - } - } - on(event, handler, thisArg, disposables) { - if (Array.isArray(event)) { - let arr = disposables || []; - for (let ev of event) { - this.on(ev, handler, thisArg, arr); - } - return vscode_languageserver_protocol_1.Disposable.create(() => { - util_1.disposeAll(arr); - }); - } - else { - let arr = this.handlers.get(event) || []; - let stack = Error().stack; - let wrappedhandler = args => new Promise((resolve, reject) => { - let timer; - try { - Promise.resolve(handler.apply(thisArg || null, args)).then(() => { - if (timer) - clearTimeout(timer); - resolve(); - }, e => { - if (timer) - clearTimeout(timer); - reject(e); - }); - timer = setTimeout(() => { - logger.warn(`Handler of ${event} blocked more than 2s:`, stack); - }, 2000); - } - catch (e) { - reject(e); - } - }); - arr.push(wrappedhandler); - this.handlers.set(event, arr); - let disposable = vscode_languageserver_protocol_1.Disposable.create(() => { - let idx = arr.indexOf(wrappedhandler); - if (idx !== -1) { - arr.splice(idx, 1); - } - }); - if (disposables) { - disposables.push(disposable); - } - return disposable; - } - } -} -exports.default = new Events(); -//# sourceMappingURL=events.js.map - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes; -exports.ResponseError = vscode_jsonrpc_1.ResponseError; -exports.CancellationToken = vscode_jsonrpc_1.CancellationToken; -exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource; -exports.Disposable = vscode_jsonrpc_1.Disposable; -exports.Event = vscode_jsonrpc_1.Event; -exports.Emitter = vscode_jsonrpc_1.Emitter; -exports.Trace = vscode_jsonrpc_1.Trace; -exports.TraceFormat = vscode_jsonrpc_1.TraceFormat; -exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification; -exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification; -exports.RequestType = vscode_jsonrpc_1.RequestType; -exports.RequestType0 = vscode_jsonrpc_1.RequestType0; -exports.NotificationType = vscode_jsonrpc_1.NotificationType; -exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0; -exports.MessageReader = vscode_jsonrpc_1.MessageReader; -exports.MessageWriter = vscode_jsonrpc_1.MessageWriter; -exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy; -exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader; -exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter; -exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader; -exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter; -exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport; -exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport; -exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName; -exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport; -exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport; -exports.ProgressType = vscode_jsonrpc_1.ProgressType; -__export(__webpack_require__(223)); -__export(__webpack_require__(224)); -const callHierarchy = __webpack_require__(236); -const st = __webpack_require__(237); -var Proposed; -(function (Proposed) { - let CallHierarchyPrepareRequest; - (function (CallHierarchyPrepareRequest) { - CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method; - CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type; - })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {})); - let CallHierarchyIncomingCallsRequest; - (function (CallHierarchyIncomingCallsRequest) { - CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method; - CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type; - })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {})); - let CallHierarchyOutgoingCallsRequest; - (function (CallHierarchyOutgoingCallsRequest) { - CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method; - CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type; - })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {})); - Proposed.SemanticTokenTypes = st.SemanticTokenTypes; - Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers; - Proposed.SemanticTokens = st.SemanticTokens; - let SemanticTokensRequest; - (function (SemanticTokensRequest) { - SemanticTokensRequest.method = st.SemanticTokensRequest.method; - SemanticTokensRequest.type = st.SemanticTokensRequest.type; - })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {})); - let SemanticTokensEditsRequest; - (function (SemanticTokensEditsRequest) { - SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method; - SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type; - })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {})); - let SemanticTokensRangeRequest; - (function (SemanticTokensRangeRequest) { - SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method; - SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type; - })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {})); -})(Proposed = exports.Proposed || (exports.Proposed = {})); -function createProtocolConnection(reader, writer, logger, strategy) { - return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy); -} -exports.createProtocolConnection = createProtocolConnection; - - -/***/ }), -/* 212 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -/// - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -const Is = __webpack_require__(213); -const messages_1 = __webpack_require__(214); -exports.RequestType = messages_1.RequestType; -exports.RequestType0 = messages_1.RequestType0; -exports.RequestType1 = messages_1.RequestType1; -exports.RequestType2 = messages_1.RequestType2; -exports.RequestType3 = messages_1.RequestType3; -exports.RequestType4 = messages_1.RequestType4; -exports.RequestType5 = messages_1.RequestType5; -exports.RequestType6 = messages_1.RequestType6; -exports.RequestType7 = messages_1.RequestType7; -exports.RequestType8 = messages_1.RequestType8; -exports.RequestType9 = messages_1.RequestType9; -exports.ResponseError = messages_1.ResponseError; -exports.ErrorCodes = messages_1.ErrorCodes; -exports.NotificationType = messages_1.NotificationType; -exports.NotificationType0 = messages_1.NotificationType0; -exports.NotificationType1 = messages_1.NotificationType1; -exports.NotificationType2 = messages_1.NotificationType2; -exports.NotificationType3 = messages_1.NotificationType3; -exports.NotificationType4 = messages_1.NotificationType4; -exports.NotificationType5 = messages_1.NotificationType5; -exports.NotificationType6 = messages_1.NotificationType6; -exports.NotificationType7 = messages_1.NotificationType7; -exports.NotificationType8 = messages_1.NotificationType8; -exports.NotificationType9 = messages_1.NotificationType9; -const messageReader_1 = __webpack_require__(215); -exports.MessageReader = messageReader_1.MessageReader; -exports.StreamMessageReader = messageReader_1.StreamMessageReader; -exports.IPCMessageReader = messageReader_1.IPCMessageReader; -exports.SocketMessageReader = messageReader_1.SocketMessageReader; -const messageWriter_1 = __webpack_require__(217); -exports.MessageWriter = messageWriter_1.MessageWriter; -exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter; -exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter; -exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter; -const events_1 = __webpack_require__(216); -exports.Disposable = events_1.Disposable; -exports.Event = events_1.Event; -exports.Emitter = events_1.Emitter; -const cancellation_1 = __webpack_require__(218); -exports.CancellationTokenSource = cancellation_1.CancellationTokenSource; -exports.CancellationToken = cancellation_1.CancellationToken; -const linkedMap_1 = __webpack_require__(219); -__export(__webpack_require__(220)); -__export(__webpack_require__(222)); -var CancelNotification; -(function (CancelNotification) { - CancelNotification.type = new messages_1.NotificationType('$/cancelRequest'); -})(CancelNotification || (CancelNotification = {})); -var ProgressNotification; -(function (ProgressNotification) { - ProgressNotification.type = new messages_1.NotificationType('$/progress'); -})(ProgressNotification || (ProgressNotification = {})); -class ProgressType { - constructor() { - } -} -exports.ProgressType = ProgressType; -exports.NullLogger = Object.freeze({ - error: () => { }, - warn: () => { }, - info: () => { }, - log: () => { } -}); -var Trace; -(function (Trace) { - Trace[Trace["Off"] = 0] = "Off"; - Trace[Trace["Messages"] = 1] = "Messages"; - Trace[Trace["Verbose"] = 2] = "Verbose"; -})(Trace = exports.Trace || (exports.Trace = {})); -(function (Trace) { - function fromString(value) { - if (!Is.string(value)) { - return Trace.Off; - } - value = value.toLowerCase(); - switch (value) { - case 'off': - return Trace.Off; - case 'messages': - return Trace.Messages; - case 'verbose': - return Trace.Verbose; - default: - return Trace.Off; - } - } - Trace.fromString = fromString; - function toString(value) { - switch (value) { - case Trace.Off: - return 'off'; - case Trace.Messages: - return 'messages'; - case Trace.Verbose: - return 'verbose'; - default: - return 'off'; - } - } - Trace.toString = toString; -})(Trace = exports.Trace || (exports.Trace = {})); -var TraceFormat; -(function (TraceFormat) { - TraceFormat["Text"] = "text"; - TraceFormat["JSON"] = "json"; -})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {})); -(function (TraceFormat) { - function fromString(value) { - value = value.toLowerCase(); - if (value === 'json') { - return TraceFormat.JSON; - } - else { - return TraceFormat.Text; - } - } - TraceFormat.fromString = fromString; -})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {})); -var SetTraceNotification; -(function (SetTraceNotification) { - SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification'); -})(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {})); -var LogTraceNotification; -(function (LogTraceNotification) { - LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification'); -})(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {})); -var ConnectionErrors; -(function (ConnectionErrors) { - /** - * The connection is closed. - */ - ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed"; - /** - * The connection got disposed. - */ - ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed"; - /** - * The connection is already in listening mode. - */ - ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening"; -})(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {})); -class ConnectionError extends Error { - constructor(code, message) { - super(message); - this.code = code; - Object.setPrototypeOf(this, ConnectionError.prototype); - } -} -exports.ConnectionError = ConnectionError; -var ConnectionStrategy; -(function (ConnectionStrategy) { - function is(value) { - let candidate = value; - return candidate && Is.func(candidate.cancelUndispatched); - } - ConnectionStrategy.is = is; -})(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {})); -var ConnectionState; -(function (ConnectionState) { - ConnectionState[ConnectionState["New"] = 1] = "New"; - ConnectionState[ConnectionState["Listening"] = 2] = "Listening"; - ConnectionState[ConnectionState["Closed"] = 3] = "Closed"; - ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed"; -})(ConnectionState || (ConnectionState = {})); -function _createMessageConnection(messageReader, messageWriter, logger, strategy) { - let sequenceNumber = 0; - let notificationSquenceNumber = 0; - let unknownResponseSquenceNumber = 0; - const version = '2.0'; - let starRequestHandler = undefined; - let requestHandlers = Object.create(null); - let starNotificationHandler = undefined; - let notificationHandlers = Object.create(null); - let progressHandlers = new Map(); - let timer; - let messageQueue = new linkedMap_1.LinkedMap(); - let responsePromises = Object.create(null); - let requestTokens = Object.create(null); - let trace = Trace.Off; - let traceFormat = TraceFormat.Text; - let tracer; - let state = ConnectionState.New; - let errorEmitter = new events_1.Emitter(); - let closeEmitter = new events_1.Emitter(); - let unhandledNotificationEmitter = new events_1.Emitter(); - let unhandledProgressEmitter = new events_1.Emitter(); - let disposeEmitter = new events_1.Emitter(); - function createRequestQueueKey(id) { - return 'req-' + id.toString(); - } - function createResponseQueueKey(id) { - if (id === null) { - return 'res-unknown-' + (++unknownResponseSquenceNumber).toString(); - } - else { - return 'res-' + id.toString(); - } - } - function createNotificationQueueKey() { - return 'not-' + (++notificationSquenceNumber).toString(); - } - function addMessageToQueue(queue, message) { - if (messages_1.isRequestMessage(message)) { - queue.set(createRequestQueueKey(message.id), message); - } - else if (messages_1.isResponseMessage(message)) { - queue.set(createResponseQueueKey(message.id), message); - } - else { - queue.set(createNotificationQueueKey(), message); - } - } - function cancelUndispatched(_message) { - return undefined; - } - function isListening() { - return state === ConnectionState.Listening; - } - function isClosed() { - return state === ConnectionState.Closed; - } - function isDisposed() { - return state === ConnectionState.Disposed; - } - function closeHandler() { - if (state === ConnectionState.New || state === ConnectionState.Listening) { - state = ConnectionState.Closed; - closeEmitter.fire(undefined); - } - // If the connection is disposed don't sent close events. - } - function readErrorHandler(error) { - errorEmitter.fire([error, undefined, undefined]); - } - function writeErrorHandler(data) { - errorEmitter.fire(data); - } - messageReader.onClose(closeHandler); - messageReader.onError(readErrorHandler); - messageWriter.onClose(closeHandler); - messageWriter.onError(writeErrorHandler); - function triggerMessageQueue() { - if (timer || messageQueue.size === 0) { - return; - } - timer = setImmediate(() => { - timer = undefined; - processMessageQueue(); - }); - } - function processMessageQueue() { - if (messageQueue.size === 0) { - return; - } - let message = messageQueue.shift(); - try { - if (messages_1.isRequestMessage(message)) { - handleRequest(message); - } - else if (messages_1.isNotificationMessage(message)) { - handleNotification(message); - } - else if (messages_1.isResponseMessage(message)) { - handleResponse(message); - } - else { - handleInvalidMessage(message); - } - } - finally { - triggerMessageQueue(); - } - } - let callback = (message) => { - try { - // We have received a cancellation message. Check if the message is still in the queue - // and cancel it if allowed to do so. - if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) { - let key = createRequestQueueKey(message.params.id); - let toCancel = messageQueue.get(key); - if (messages_1.isRequestMessage(toCancel)) { - let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); - if (response && (response.error !== void 0 || response.result !== void 0)) { - messageQueue.delete(key); - response.id = toCancel.id; - traceSendingResponse(response, message.method, Date.now()); - messageWriter.write(response); - return; - } - } - } - addMessageToQueue(messageQueue, message); - } - finally { - triggerMessageQueue(); - } - }; - function handleRequest(requestMessage) { - if (isDisposed()) { - // we return here silently since we fired an event when the - // connection got disposed. - return; - } - function reply(resultOrError, method, startTime) { - let message = { - jsonrpc: version, - id: requestMessage.id - }; - if (resultOrError instanceof messages_1.ResponseError) { - message.error = resultOrError.toJson(); - } - else { - message.result = resultOrError === void 0 ? null : resultOrError; - } - traceSendingResponse(message, method, startTime); - messageWriter.write(message); - } - function replyError(error, method, startTime) { - let message = { - jsonrpc: version, - id: requestMessage.id, - error: error.toJson() - }; - traceSendingResponse(message, method, startTime); - messageWriter.write(message); - } - function replySuccess(result, method, startTime) { - // The JSON RPC defines that a response must either have a result or an error - // So we can't treat undefined as a valid response result. - if (result === void 0) { - result = null; - } - let message = { - jsonrpc: version, - id: requestMessage.id, - result: result - }; - traceSendingResponse(message, method, startTime); - messageWriter.write(message); - } - traceReceivedRequest(requestMessage); - let element = requestHandlers[requestMessage.method]; - let type; - let requestHandler; - if (element) { - type = element.type; - requestHandler = element.handler; - } - let startTime = Date.now(); - if (requestHandler || starRequestHandler) { - let cancellationSource = new cancellation_1.CancellationTokenSource(); - let tokenKey = String(requestMessage.id); - requestTokens[tokenKey] = cancellationSource; - try { - let handlerResult; - if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) { - handlerResult = requestHandler - ? requestHandler(cancellationSource.token) - : starRequestHandler(requestMessage.method, cancellationSource.token); - } - else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) { - handlerResult = requestHandler - ? requestHandler(...requestMessage.params, cancellationSource.token) - : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token); - } - else { - handlerResult = requestHandler - ? requestHandler(requestMessage.params, cancellationSource.token) - : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); - } - let promise = handlerResult; - if (!handlerResult) { - delete requestTokens[tokenKey]; - replySuccess(handlerResult, requestMessage.method, startTime); - } - else if (promise.then) { - promise.then((resultOrError) => { - delete requestTokens[tokenKey]; - reply(resultOrError, requestMessage.method, startTime); - }, error => { - delete requestTokens[tokenKey]; - if (error instanceof messages_1.ResponseError) { - replyError(error, requestMessage.method, startTime); - } - else if (error && Is.string(error.message)) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); - } - else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); - } - }); - } - else { - delete requestTokens[tokenKey]; - reply(handlerResult, requestMessage.method, startTime); - } - } - catch (error) { - delete requestTokens[tokenKey]; - if (error instanceof messages_1.ResponseError) { - reply(error, requestMessage.method, startTime); - } - else if (error && Is.string(error.message)) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); - } - else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); - } - } - } - else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime); - } - } - function handleResponse(responseMessage) { - if (isDisposed()) { - // See handle request. - return; - } - if (responseMessage.id === null) { - if (responseMessage.error) { - logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`); - } - else { - logger.error(`Received response message without id. No further error information provided.`); - } - } - else { - let key = String(responseMessage.id); - let responsePromise = responsePromises[key]; - traceReceivedResponse(responseMessage, responsePromise); - if (responsePromise) { - delete responsePromises[key]; - try { - if (responseMessage.error) { - let error = responseMessage.error; - responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); - } - else if (responseMessage.result !== void 0) { - responsePromise.resolve(responseMessage.result); - } - else { - throw new Error('Should never happen.'); - } - } - catch (error) { - if (error.message) { - logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`); - } - else { - logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`); - } - } - } - } - } - function handleNotification(message) { - if (isDisposed()) { - // See handle request. - return; - } - let type = undefined; - let notificationHandler; - if (message.method === CancelNotification.type.method) { - notificationHandler = (params) => { - let id = params.id; - let source = requestTokens[String(id)]; - if (source) { - source.cancel(); - } - }; - } - else { - let element = notificationHandlers[message.method]; - if (element) { - notificationHandler = element.handler; - type = element.type; - } - } - if (notificationHandler || starNotificationHandler) { - try { - traceReceivedNotification(message); - if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) { - notificationHandler ? notificationHandler() : starNotificationHandler(message.method); - } - else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) { - notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params); - } - else { - notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params); - } - } - catch (error) { - if (error.message) { - logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`); - } - else { - logger.error(`Notification handler '${message.method}' failed unexpectedly.`); - } - } - } - else { - unhandledNotificationEmitter.fire(message); - } - } - function handleInvalidMessage(message) { - if (!message) { - logger.error('Received empty message.'); - return; - } - logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`); - // Test whether we find an id to reject the promise - let responseMessage = message; - if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) { - let key = String(responseMessage.id); - let responseHandler = responsePromises[key]; - if (responseHandler) { - responseHandler.reject(new Error('The received response has neither a result nor an error property.')); - } - } - } - function traceSendingRequest(message) { - if (trace === Trace.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose && message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; - } - tracer.log(`Sending request '${message.method} - (${message.id})'.`, data); - } - else { - logLSPMessage('send-request', message); - } - } - function traceSendingNotification(message) { - if (trace === Trace.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose) { - if (message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; - } - else { - data = 'No parameters provided.\n\n'; - } - } - tracer.log(`Sending notification '${message.method}'.`, data); - } - else { - logLSPMessage('send-notification', message); - } - } - function traceSendingResponse(message, method, startTime) { - if (trace === Trace.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose) { - if (message.error && message.error.data) { - data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`; - } - else { - if (message.result) { - data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`; - } - else if (message.error === void 0) { - data = 'No result returned.\n\n'; - } - } - } - tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data); - } - else { - logLSPMessage('send-response', message); - } - } - function traceReceivedRequest(message) { - if (trace === Trace.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose && message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; - } - tracer.log(`Received request '${message.method} - (${message.id})'.`, data); - } - else { - logLSPMessage('receive-request', message); - } - } - function traceReceivedNotification(message) { - if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose) { - if (message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; - } - else { - data = 'No parameters provided.\n\n'; - } - } - tracer.log(`Received notification '${message.method}'.`, data); - } - else { - logLSPMessage('receive-notification', message); - } - } - function traceReceivedResponse(message, responsePromise) { - if (trace === Trace.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat.Text) { - let data = undefined; - if (trace === Trace.Verbose) { - if (message.error && message.error.data) { - data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`; - } - else { - if (message.result) { - data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`; - } - else if (message.error === void 0) { - data = 'No result returned.\n\n'; - } - } - } - if (responsePromise) { - let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : ''; - tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data); - } - else { - tracer.log(`Received response ${message.id} without active response promise.`, data); - } - } - else { - logLSPMessage('receive-response', message); - } - } - function logLSPMessage(type, message) { - if (!tracer || trace === Trace.Off) { - return; - } - const lspMessage = { - isLSPMessage: true, - type, - message, - timestamp: Date.now() - }; - tracer.log(lspMessage); - } - function throwIfClosedOrDisposed() { - if (isClosed()) { - throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.'); - } - if (isDisposed()) { - throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.'); - } - } - function throwIfListening() { - if (isListening()) { - throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening'); - } - } - function throwIfNotListening() { - if (!isListening()) { - throw new Error('Call listen() first.'); - } - } - function undefinedToNull(param) { - if (param === void 0) { - return null; - } - else { - return param; - } - } - function computeMessageParams(type, params) { - let result; - let numberOfParams = type.numberOfParams; - switch (numberOfParams) { - case 0: - result = null; - break; - case 1: - result = undefinedToNull(params[0]); - break; - default: - result = []; - for (let i = 0; i < params.length && i < numberOfParams; i++) { - result.push(undefinedToNull(params[i])); - } - if (params.length < numberOfParams) { - for (let i = params.length; i < numberOfParams; i++) { - result.push(null); - } - } - break; - } - return result; - } - let connection = { - sendNotification: (type, ...params) => { - throwIfClosedOrDisposed(); - let method; - let messageParams; - if (Is.string(type)) { - method = type; - switch (params.length) { - case 0: - messageParams = null; - break; - case 1: - messageParams = params[0]; - break; - default: - messageParams = params; - break; - } - } - else { - method = type.method; - messageParams = computeMessageParams(type, params); - } - let notificationMessage = { - jsonrpc: version, - method: method, - params: messageParams - }; - traceSendingNotification(notificationMessage); - messageWriter.write(notificationMessage); - }, - onNotification: (type, handler) => { - throwIfClosedOrDisposed(); - if (Is.func(type)) { - starNotificationHandler = type; - } - else if (handler) { - if (Is.string(type)) { - notificationHandlers[type] = { type: undefined, handler }; - } - else { - notificationHandlers[type.method] = { type, handler }; - } - } - }, - onProgress: (_type, token, handler) => { - if (progressHandlers.has(token)) { - throw new Error(`Progress handler for token ${token} already registered`); - } - progressHandlers.set(token, handler); - return { - dispose: () => { - progressHandlers.delete(token); - } - }; - }, - sendProgress: (_type, token, value) => { - connection.sendNotification(ProgressNotification.type, { token, value }); - }, - onUnhandledProgress: unhandledProgressEmitter.event, - sendRequest: (type, ...params) => { - throwIfClosedOrDisposed(); - throwIfNotListening(); - let method; - let messageParams; - let token = undefined; - if (Is.string(type)) { - method = type; - switch (params.length) { - case 0: - messageParams = null; - break; - case 1: - // The cancellation token is optional so it can also be undefined. - if (cancellation_1.CancellationToken.is(params[0])) { - messageParams = null; - token = params[0]; - } - else { - messageParams = undefinedToNull(params[0]); - } - break; - default: - const last = params.length - 1; - if (cancellation_1.CancellationToken.is(params[last])) { - token = params[last]; - if (params.length === 2) { - messageParams = undefinedToNull(params[0]); - } - else { - messageParams = params.slice(0, last).map(value => undefinedToNull(value)); - } - } - else { - messageParams = params.map(value => undefinedToNull(value)); - } - break; - } - } - else { - method = type.method; - messageParams = computeMessageParams(type, params); - let numberOfParams = type.numberOfParams; - token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined; - } - let id = sequenceNumber++; - let result = new Promise((resolve, reject) => { - let requestMessage = { - jsonrpc: version, - id: id, - method: method, - params: messageParams - }; - let responsePromise = { method: method, timerStart: Date.now(), resolve, reject }; - traceSendingRequest(requestMessage); - try { - messageWriter.write(requestMessage); - } - catch (e) { - // Writing the message failed. So we need to reject the promise. - responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason')); - responsePromise = null; - } - if (responsePromise) { - responsePromises[String(id)] = responsePromise; - } - }); - if (token) { - token.onCancellationRequested(() => { - connection.sendNotification(CancelNotification.type, { id }); - }); - } - return result; - }, - onRequest: (type, handler) => { - throwIfClosedOrDisposed(); - if (Is.func(type)) { - starRequestHandler = type; - } - else if (handler) { - if (Is.string(type)) { - requestHandlers[type] = { type: undefined, handler }; - } - else { - requestHandlers[type.method] = { type, handler }; - } - } - }, - trace: (_value, _tracer, sendNotificationOrTraceOptions) => { - let _sendNotification = false; - let _traceFormat = TraceFormat.Text; - if (sendNotificationOrTraceOptions !== void 0) { - if (Is.boolean(sendNotificationOrTraceOptions)) { - _sendNotification = sendNotificationOrTraceOptions; - } - else { - _sendNotification = sendNotificationOrTraceOptions.sendNotification || false; - _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text; - } - } - trace = _value; - traceFormat = _traceFormat; - if (trace === Trace.Off) { - tracer = undefined; - } - else { - tracer = _tracer; - } - if (_sendNotification && !isClosed() && !isDisposed()) { - connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) }); - } - }, - onError: errorEmitter.event, - onClose: closeEmitter.event, - onUnhandledNotification: unhandledNotificationEmitter.event, - onDispose: disposeEmitter.event, - dispose: () => { - if (isDisposed()) { - return; - } - state = ConnectionState.Disposed; - disposeEmitter.fire(undefined); - let error = new Error('Connection got disposed.'); - Object.keys(responsePromises).forEach((key) => { - responsePromises[key].reject(error); - }); - responsePromises = Object.create(null); - requestTokens = Object.create(null); - messageQueue = new linkedMap_1.LinkedMap(); - // Test for backwards compatibility - if (Is.func(messageWriter.dispose)) { - messageWriter.dispose(); - } - if (Is.func(messageReader.dispose)) { - messageReader.dispose(); - } - }, - listen: () => { - throwIfClosedOrDisposed(); - throwIfListening(); - state = ConnectionState.Listening; - messageReader.listen(callback); - }, - inspect: () => { - // eslint-disable-next-line no-console - console.log('inspect'); - } - }; - connection.onNotification(LogTraceNotification.type, (params) => { - if (trace === Trace.Off || !tracer) { - return; - } - tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined); - }); - connection.onNotification(ProgressNotification.type, (params) => { - const handler = progressHandlers.get(params.token); - if (handler) { - handler(params.value); - } - else { - unhandledProgressEmitter.fire(params); - } - }); - return connection; -} -function isMessageReader(value) { - return value.listen !== void 0 && value.read === void 0; -} -function isMessageWriter(value) { - return value.write !== void 0 && value.end === void 0; -} -function createMessageConnection(input, output, logger, strategy) { - if (!logger) { - logger = exports.NullLogger; - } - let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input); - let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output); - return _createMessageConnection(reader, writer, logger, strategy); -} -exports.createMessageConnection = createMessageConnection; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -function boolean(value) { - return value === true || value === false; -} -exports.boolean = boolean; -function string(value) { - return typeof value === 'string' || value instanceof String; -} -exports.string = string; -function number(value) { - return typeof value === 'number' || value instanceof Number; -} -exports.number = number; -function error(value) { - return value instanceof Error; -} -exports.error = error; -function func(value) { - return typeof value === 'function'; -} -exports.func = func; -function array(value) { - return Array.isArray(value); -} -exports.array = array; -function stringArray(value) { - return array(value) && value.every(elem => string(elem)); -} -exports.stringArray = stringArray; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const is = __webpack_require__(213); -/** - * Predefined error codes. - */ -var ErrorCodes; -(function (ErrorCodes) { - // Defined by JSON RPC - ErrorCodes.ParseError = -32700; - ErrorCodes.InvalidRequest = -32600; - ErrorCodes.MethodNotFound = -32601; - ErrorCodes.InvalidParams = -32602; - ErrorCodes.InternalError = -32603; - ErrorCodes.serverErrorStart = -32099; - ErrorCodes.serverErrorEnd = -32000; - ErrorCodes.ServerNotInitialized = -32002; - ErrorCodes.UnknownErrorCode = -32001; - // Defined by the protocol. - ErrorCodes.RequestCancelled = -32800; - ErrorCodes.ContentModified = -32801; - // Defined by VSCode library. - ErrorCodes.MessageWriteError = 1; - ErrorCodes.MessageReadError = 2; -})(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {})); -/** - * An error object return in a response in case a request - * has failed. - */ -class ResponseError extends Error { - constructor(code, message, data) { - super(message); - this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode; - this.data = data; - Object.setPrototypeOf(this, ResponseError.prototype); - } - toJson() { - return { - code: this.code, - message: this.message, - data: this.data, - }; - } -} -exports.ResponseError = ResponseError; -/** - * An abstract implementation of a MessageType. - */ -class AbstractMessageType { - constructor(_method, _numberOfParams) { - this._method = _method; - this._numberOfParams = _numberOfParams; - } - get method() { - return this._method; - } - get numberOfParams() { - return this._numberOfParams; - } -} -exports.AbstractMessageType = AbstractMessageType; -/** - * Classes to type request response pairs - * - * The type parameter RO will be removed in the next major version - * of the JSON RPC library since it is a LSP concept and doesn't - * belong here. For now it is tagged as default never. - */ -class RequestType0 extends AbstractMessageType { - constructor(method) { - super(method, 0); - } -} -exports.RequestType0 = RequestType0; -class RequestType extends AbstractMessageType { - constructor(method) { - super(method, 1); - } -} -exports.RequestType = RequestType; -class RequestType1 extends AbstractMessageType { - constructor(method) { - super(method, 1); - } -} -exports.RequestType1 = RequestType1; -class RequestType2 extends AbstractMessageType { - constructor(method) { - super(method, 2); - } -} -exports.RequestType2 = RequestType2; -class RequestType3 extends AbstractMessageType { - constructor(method) { - super(method, 3); - } -} -exports.RequestType3 = RequestType3; -class RequestType4 extends AbstractMessageType { - constructor(method) { - super(method, 4); - } -} -exports.RequestType4 = RequestType4; -class RequestType5 extends AbstractMessageType { - constructor(method) { - super(method, 5); - } -} -exports.RequestType5 = RequestType5; -class RequestType6 extends AbstractMessageType { - constructor(method) { - super(method, 6); - } -} -exports.RequestType6 = RequestType6; -class RequestType7 extends AbstractMessageType { - constructor(method) { - super(method, 7); - } -} -exports.RequestType7 = RequestType7; -class RequestType8 extends AbstractMessageType { - constructor(method) { - super(method, 8); - } -} -exports.RequestType8 = RequestType8; -class RequestType9 extends AbstractMessageType { - constructor(method) { - super(method, 9); - } -} -exports.RequestType9 = RequestType9; -/** - * The type parameter RO will be removed in the next major version - * of the JSON RPC library since it is a LSP concept and doesn't - * belong here. For now it is tagged as default never. - */ -class NotificationType extends AbstractMessageType { - constructor(method) { - super(method, 1); - this._ = undefined; - } -} -exports.NotificationType = NotificationType; -class NotificationType0 extends AbstractMessageType { - constructor(method) { - super(method, 0); - } -} -exports.NotificationType0 = NotificationType0; -class NotificationType1 extends AbstractMessageType { - constructor(method) { - super(method, 1); - } -} -exports.NotificationType1 = NotificationType1; -class NotificationType2 extends AbstractMessageType { - constructor(method) { - super(method, 2); - } -} -exports.NotificationType2 = NotificationType2; -class NotificationType3 extends AbstractMessageType { - constructor(method) { - super(method, 3); - } -} -exports.NotificationType3 = NotificationType3; -class NotificationType4 extends AbstractMessageType { - constructor(method) { - super(method, 4); - } -} -exports.NotificationType4 = NotificationType4; -class NotificationType5 extends AbstractMessageType { - constructor(method) { - super(method, 5); - } -} -exports.NotificationType5 = NotificationType5; -class NotificationType6 extends AbstractMessageType { - constructor(method) { - super(method, 6); - } -} -exports.NotificationType6 = NotificationType6; -class NotificationType7 extends AbstractMessageType { - constructor(method) { - super(method, 7); - } -} -exports.NotificationType7 = NotificationType7; -class NotificationType8 extends AbstractMessageType { - constructor(method) { - super(method, 8); - } -} -exports.NotificationType8 = NotificationType8; -class NotificationType9 extends AbstractMessageType { - constructor(method) { - super(method, 9); - } -} -exports.NotificationType9 = NotificationType9; -/** - * Tests if the given message is a request message - */ -function isRequestMessage(message) { - let candidate = message; - return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id)); -} -exports.isRequestMessage = isRequestMessage; -/** - * Tests if the given message is a notification message - */ -function isNotificationMessage(message) { - let candidate = message; - return candidate && is.string(candidate.method) && message.id === void 0; -} -exports.isNotificationMessage = isNotificationMessage; -/** - * Tests if the given message is a response message - */ -function isResponseMessage(message) { - let candidate = message; - return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null); -} -exports.isResponseMessage = isResponseMessage; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(216); -const Is = __webpack_require__(213); -let DefaultSize = 8192; -let CR = Buffer.from('\r', 'ascii')[0]; -let LF = Buffer.from('\n', 'ascii')[0]; -let CRLF = '\r\n'; -class MessageBuffer { - constructor(encoding = 'utf8') { - this.encoding = encoding; - this.index = 0; - this.buffer = Buffer.allocUnsafe(DefaultSize); - } - append(chunk) { - var toAppend = chunk; - if (typeof (chunk) === 'string') { - var str = chunk; - var bufferLen = Buffer.byteLength(str, this.encoding); - toAppend = Buffer.allocUnsafe(bufferLen); - toAppend.write(str, 0, bufferLen, this.encoding); - } - if (this.buffer.length - this.index >= toAppend.length) { - toAppend.copy(this.buffer, this.index, 0, toAppend.length); - } - else { - var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize; - if (this.index === 0) { - this.buffer = Buffer.allocUnsafe(newSize); - toAppend.copy(this.buffer, 0, 0, toAppend.length); - } - else { - this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize); - } - } - this.index += toAppend.length; - } - tryReadHeaders() { - let result = undefined; - let current = 0; - while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) { - current++; - } - // No header / body separator found (e.g CRLFCRLF) - if (current + 3 >= this.index) { - return result; - } - result = Object.create(null); - let headers = this.buffer.toString('ascii', 0, current).split(CRLF); - headers.forEach((header) => { - let index = header.indexOf(':'); - if (index === -1) { - throw new Error('Message header must separate key and value using :'); - } - let key = header.substr(0, index); - let value = header.substr(index + 1).trim(); - result[key] = value; - }); - let nextStart = current + 4; - this.buffer = this.buffer.slice(nextStart); - this.index = this.index - nextStart; - return result; - } - tryReadContent(length) { - if (this.index < length) { - return null; - } - let result = this.buffer.toString(this.encoding, 0, length); - let nextStart = length; - this.buffer.copy(this.buffer, 0, nextStart); - this.index = this.index - nextStart; - return result; - } - get numberOfBytes() { - return this.index; - } -} -var MessageReader; -(function (MessageReader) { - function is(value) { - let candidate = value; - return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && - Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage); - } - MessageReader.is = is; -})(MessageReader = exports.MessageReader || (exports.MessageReader = {})); -class AbstractMessageReader { - constructor() { - this.errorEmitter = new events_1.Emitter(); - this.closeEmitter = new events_1.Emitter(); - this.partialMessageEmitter = new events_1.Emitter(); - } - dispose() { - this.errorEmitter.dispose(); - this.closeEmitter.dispose(); - } - get onError() { - return this.errorEmitter.event; - } - fireError(error) { - this.errorEmitter.fire(this.asError(error)); - } - get onClose() { - return this.closeEmitter.event; - } - fireClose() { - this.closeEmitter.fire(undefined); - } - get onPartialMessage() { - return this.partialMessageEmitter.event; - } - firePartialMessage(info) { - this.partialMessageEmitter.fire(info); - } - asError(error) { - if (error instanceof Error) { - return error; - } - else { - return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); - } - } -} -exports.AbstractMessageReader = AbstractMessageReader; -class StreamMessageReader extends AbstractMessageReader { - constructor(readable, encoding = 'utf8') { - super(); - this.readable = readable; - this.buffer = new MessageBuffer(encoding); - this._partialMessageTimeout = 10000; - } - set partialMessageTimeout(timeout) { - this._partialMessageTimeout = timeout; - } - get partialMessageTimeout() { - return this._partialMessageTimeout; - } - listen(callback) { - this.nextMessageLength = -1; - this.messageToken = 0; - this.partialMessageTimer = undefined; - this.callback = callback; - this.readable.on('data', (data) => { - this.onData(data); - }); - this.readable.on('error', (error) => this.fireError(error)); - this.readable.on('close', () => this.fireClose()); - } - onData(data) { - this.buffer.append(data); - while (true) { - if (this.nextMessageLength === -1) { - let headers = this.buffer.tryReadHeaders(); - if (!headers) { - return; - } - let contentLength = headers['Content-Length']; - if (!contentLength) { - throw new Error('Header must provide a Content-Length property.'); - } - let length = parseInt(contentLength); - if (isNaN(length)) { - throw new Error('Content-Length value must be a number.'); - } - this.nextMessageLength = length; - // Take the encoding form the header. For compatibility - // treat both utf-8 and utf8 as node utf8 - } - var msg = this.buffer.tryReadContent(this.nextMessageLength); - if (msg === null) { - /** We haven't received the full message yet. */ - this.setPartialMessageTimer(); - return; - } - this.clearPartialMessageTimer(); - this.nextMessageLength = -1; - this.messageToken++; - var json = JSON.parse(msg); - this.callback(json); - } - } - clearPartialMessageTimer() { - if (this.partialMessageTimer) { - clearTimeout(this.partialMessageTimer); - this.partialMessageTimer = undefined; - } - } - setPartialMessageTimer() { - this.clearPartialMessageTimer(); - if (this._partialMessageTimeout <= 0) { - return; - } - this.partialMessageTimer = setTimeout((token, timeout) => { - this.partialMessageTimer = undefined; - if (token === this.messageToken) { - this.firePartialMessage({ messageToken: token, waitingTime: timeout }); - this.setPartialMessageTimer(); - } - }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout); - } -} -exports.StreamMessageReader = StreamMessageReader; -class IPCMessageReader extends AbstractMessageReader { - constructor(process) { - super(); - this.process = process; - let eventEmitter = this.process; - eventEmitter.on('error', (error) => this.fireError(error)); - eventEmitter.on('close', () => this.fireClose()); - } - listen(callback) { - this.process.on('message', callback); - } -} -exports.IPCMessageReader = IPCMessageReader; -class SocketMessageReader extends StreamMessageReader { - constructor(socket, encoding = 'utf-8') { - super(socket, encoding); - } -} -exports.SocketMessageReader = SocketMessageReader; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -var Disposable; -(function (Disposable) { - function create(func) { - return { - dispose: func - }; - } - Disposable.create = create; -})(Disposable = exports.Disposable || (exports.Disposable = {})); -var Event; -(function (Event) { - const _disposable = { dispose() { } }; - Event.None = function () { return _disposable; }; -})(Event = exports.Event || (exports.Event = {})); -class CallbackList { - add(callback, context = null, bucket) { - if (!this._callbacks) { - this._callbacks = []; - this._contexts = []; - } - this._callbacks.push(callback); - this._contexts.push(context); - if (Array.isArray(bucket)) { - bucket.push({ dispose: () => this.remove(callback, context) }); - } - } - remove(callback, context = null) { - if (!this._callbacks) { - return; - } - var foundCallbackWithDifferentContext = false; - for (var i = 0, len = this._callbacks.length; i < len; i++) { - if (this._callbacks[i] === callback) { - if (this._contexts[i] === context) { - // callback & context match => remove it - this._callbacks.splice(i, 1); - this._contexts.splice(i, 1); - return; - } - else { - foundCallbackWithDifferentContext = true; - } - } - } - if (foundCallbackWithDifferentContext) { - throw new Error('When adding a listener with a context, you should remove it with the same context'); - } - } - invoke(...args) { - if (!this._callbacks) { - return []; - } - var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0); - for (var i = 0, len = callbacks.length; i < len; i++) { - try { - ret.push(callbacks[i].apply(contexts[i], args)); - } - catch (e) { - // eslint-disable-next-line no-console - console.error(e); - } - } - return ret; - } - isEmpty() { - return !this._callbacks || this._callbacks.length === 0; - } - dispose() { - this._callbacks = undefined; - this._contexts = undefined; - } -} -class Emitter { - constructor(_options) { - this._options = _options; - } - /** - * For the public to allow to subscribe - * to events from this Emitter - */ - get event() { - if (!this._event) { - this._event = (listener, thisArgs, disposables) => { - if (!this._callbacks) { - this._callbacks = new CallbackList(); - } - if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) { - this._options.onFirstListenerAdd(this); - } - this._callbacks.add(listener, thisArgs); - let result; - result = { - dispose: () => { - this._callbacks.remove(listener, thisArgs); - result.dispose = Emitter._noop; - if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { - this._options.onLastListenerRemove(this); - } - } - }; - if (Array.isArray(disposables)) { - disposables.push(result); - } - return result; - }; - } - return this._event; - } - /** - * To be kept private to fire an event to - * subscribers - */ - fire(event) { - if (this._callbacks) { - this._callbacks.invoke.call(this._callbacks, event); - } - } - dispose() { - if (this._callbacks) { - this._callbacks.dispose(); - this._callbacks = undefined; - } - } -} -exports.Emitter = Emitter; -Emitter._noop = function () { }; - - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(216); -const Is = __webpack_require__(213); -let ContentLength = 'Content-Length: '; -let CRLF = '\r\n'; -var MessageWriter; -(function (MessageWriter) { - function is(value) { - let candidate = value; - return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && - Is.func(candidate.onError) && Is.func(candidate.write); - } - MessageWriter.is = is; -})(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {})); -class AbstractMessageWriter { - constructor() { - this.errorEmitter = new events_1.Emitter(); - this.closeEmitter = new events_1.Emitter(); - } - dispose() { - this.errorEmitter.dispose(); - this.closeEmitter.dispose(); - } - get onError() { - return this.errorEmitter.event; - } - fireError(error, message, count) { - this.errorEmitter.fire([this.asError(error), message, count]); - } - get onClose() { - return this.closeEmitter.event; - } - fireClose() { - this.closeEmitter.fire(undefined); - } - asError(error) { - if (error instanceof Error) { - return error; - } - else { - return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); - } - } -} -exports.AbstractMessageWriter = AbstractMessageWriter; -class StreamMessageWriter extends AbstractMessageWriter { - constructor(writable, encoding = 'utf8') { - super(); - this.writable = writable; - this.encoding = encoding; - this.errorCount = 0; - this.writable.on('error', (error) => this.fireError(error)); - this.writable.on('close', () => this.fireClose()); - } - write(msg) { - let json = JSON.stringify(msg); - let contentLength = Buffer.byteLength(json, this.encoding); - let headers = [ - ContentLength, contentLength.toString(), CRLF, - CRLF - ]; - try { - // Header must be written in ASCII encoding - this.writable.write(headers.join(''), 'ascii'); - // Now write the content. This can be written in any encoding - this.writable.write(json, this.encoding); - this.errorCount = 0; - } - catch (error) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } - } -} -exports.StreamMessageWriter = StreamMessageWriter; -class IPCMessageWriter extends AbstractMessageWriter { - constructor(process) { - super(); - this.process = process; - this.errorCount = 0; - this.queue = []; - this.sending = false; - let eventEmitter = this.process; - eventEmitter.on('error', (error) => this.fireError(error)); - eventEmitter.on('close', () => this.fireClose); - } - write(msg) { - if (!this.sending && this.queue.length === 0) { - // See https://github.com/nodejs/node/issues/7657 - this.doWriteMessage(msg); - } - else { - this.queue.push(msg); - } - } - doWriteMessage(msg) { - try { - if (this.process.send) { - this.sending = true; - this.process.send(msg, undefined, undefined, (error) => { - this.sending = false; - if (error) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } - else { - this.errorCount = 0; - } - if (this.queue.length > 0) { - this.doWriteMessage(this.queue.shift()); - } - }); - } - } - catch (error) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } - } -} -exports.IPCMessageWriter = IPCMessageWriter; -class SocketMessageWriter extends AbstractMessageWriter { - constructor(socket, encoding = 'utf8') { - super(); - this.socket = socket; - this.queue = []; - this.sending = false; - this.encoding = encoding; - this.errorCount = 0; - this.socket.on('error', (error) => this.fireError(error)); - this.socket.on('close', () => this.fireClose()); - } - dispose() { - super.dispose(); - this.socket.destroy(); - } - write(msg) { - if (!this.sending && this.queue.length === 0) { - // See https://github.com/nodejs/node/issues/7657 - this.doWriteMessage(msg); - } - else { - this.queue.push(msg); - } - } - doWriteMessage(msg) { - let json = JSON.stringify(msg); - let contentLength = Buffer.byteLength(json, this.encoding); - let headers = [ - ContentLength, contentLength.toString(), CRLF, - CRLF - ]; - try { - // Header must be written in ASCII encoding - this.sending = true; - this.socket.write(headers.join(''), 'ascii', (error) => { - if (error) { - this.handleError(error, msg); - } - try { - // Now write the content. This can be written in any encoding - this.socket.write(json, this.encoding, (error) => { - this.sending = false; - if (error) { - this.handleError(error, msg); - } - else { - this.errorCount = 0; - } - if (this.queue.length > 0) { - this.doWriteMessage(this.queue.shift()); - } - }); - } - catch (error) { - this.handleError(error, msg); - } - }); - } - catch (error) { - this.handleError(error, msg); - } - } - handleError(error, msg) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } -} -exports.SocketMessageWriter = SocketMessageWriter; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(216); -const Is = __webpack_require__(213); -var CancellationToken; -(function (CancellationToken) { - CancellationToken.None = Object.freeze({ - isCancellationRequested: false, - onCancellationRequested: events_1.Event.None - }); - CancellationToken.Cancelled = Object.freeze({ - isCancellationRequested: true, - onCancellationRequested: events_1.Event.None - }); - function is(value) { - let candidate = value; - return candidate && (candidate === CancellationToken.None - || candidate === CancellationToken.Cancelled - || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested)); - } - CancellationToken.is = is; -})(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {})); -const shortcutEvent = Object.freeze(function (callback, context) { - let handle = setTimeout(callback.bind(context), 0); - return { dispose() { clearTimeout(handle); } }; -}); -class MutableToken { - constructor() { - this._isCancelled = false; - } - cancel() { - if (!this._isCancelled) { - this._isCancelled = true; - if (this._emitter) { - this._emitter.fire(undefined); - this.dispose(); - } - } - } - get isCancellationRequested() { - return this._isCancelled; - } - get onCancellationRequested() { - if (this._isCancelled) { - return shortcutEvent; - } - if (!this._emitter) { - this._emitter = new events_1.Emitter(); - } - return this._emitter.event; - } - dispose() { - if (this._emitter) { - this._emitter.dispose(); - this._emitter = undefined; - } - } -} -class CancellationTokenSource { - get token() { - if (!this._token) { - // be lazy and create the token only when - // actually needed - this._token = new MutableToken(); - } - return this._token; - } - cancel() { - if (!this._token) { - // save an object by returning the default - // cancelled token when cancellation happens - // before someone asks for the token - this._token = CancellationToken.Cancelled; - } - else { - this._token.cancel(); - } - } - dispose() { - if (!this._token) { - // ensure to initialize with an empty token if we had none - this._token = CancellationToken.None; - } - else if (this._token instanceof MutableToken) { - // actually dispose - this._token.dispose(); - } - } -} -exports.CancellationTokenSource = CancellationTokenSource; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -var Touch; -(function (Touch) { - Touch.None = 0; - Touch.First = 1; - Touch.Last = 2; -})(Touch = exports.Touch || (exports.Touch = {})); -class LinkedMap { - constructor() { - this._map = new Map(); - this._head = undefined; - this._tail = undefined; - this._size = 0; - } - clear() { - this._map.clear(); - this._head = undefined; - this._tail = undefined; - this._size = 0; - } - isEmpty() { - return !this._head && !this._tail; - } - get size() { - return this._size; - } - has(key) { - return this._map.has(key); - } - get(key) { - const item = this._map.get(key); - if (!item) { - return undefined; - } - return item.value; - } - set(key, value, touch = Touch.None) { - let item = this._map.get(key); - if (item) { - item.value = value; - if (touch !== Touch.None) { - this.touch(item, touch); - } - } - else { - item = { key, value, next: undefined, previous: undefined }; - switch (touch) { - case Touch.None: - this.addItemLast(item); - break; - case Touch.First: - this.addItemFirst(item); - break; - case Touch.Last: - this.addItemLast(item); - break; - default: - this.addItemLast(item); - break; - } - this._map.set(key, item); - this._size++; - } - } - delete(key) { - const item = this._map.get(key); - if (!item) { - return false; - } - this._map.delete(key); - this.removeItem(item); - this._size--; - return true; - } - shift() { - if (!this._head && !this._tail) { - return undefined; - } - if (!this._head || !this._tail) { - throw new Error('Invalid list'); - } - const item = this._head; - this._map.delete(item.key); - this.removeItem(item); - this._size--; - return item.value; - } - forEach(callbackfn, thisArg) { - let current = this._head; - while (current) { - if (thisArg) { - callbackfn.bind(thisArg)(current.value, current.key, this); - } - else { - callbackfn(current.value, current.key, this); - } - current = current.next; - } - } - forEachReverse(callbackfn, thisArg) { - let current = this._tail; - while (current) { - if (thisArg) { - callbackfn.bind(thisArg)(current.value, current.key, this); - } - else { - callbackfn(current.value, current.key, this); - } - current = current.previous; - } - } - values() { - let result = []; - let current = this._head; - while (current) { - result.push(current.value); - current = current.next; - } - return result; - } - keys() { - let result = []; - let current = this._head; - while (current) { - result.push(current.key); - current = current.next; - } - return result; - } - /* JSON RPC run on es5 which has no Symbol.iterator - public keys(): IterableIterator { - let current = this._head; - let iterator: IterableIterator = { - [Symbol.iterator]() { - return iterator; - }, - next():IteratorResult { - if (current) { - let result = { value: current.key, done: false }; - current = current.next; - return result; - } else { - return { value: undefined, done: true }; - } - } - }; - return iterator; - } - - public values(): IterableIterator { - let current = this._head; - let iterator: IterableIterator = { - [Symbol.iterator]() { - return iterator; - }, - next():IteratorResult { - if (current) { - let result = { value: current.value, done: false }; - current = current.next; - return result; - } else { - return { value: undefined, done: true }; - } - } - }; - return iterator; - } - */ - addItemFirst(item) { - // First time Insert - if (!this._head && !this._tail) { - this._tail = item; - } - else if (!this._head) { - throw new Error('Invalid list'); - } - else { - item.next = this._head; - this._head.previous = item; - } - this._head = item; - } - addItemLast(item) { - // First time Insert - if (!this._head && !this._tail) { - this._head = item; - } - else if (!this._tail) { - throw new Error('Invalid list'); - } - else { - item.previous = this._tail; - this._tail.next = item; - } - this._tail = item; - } - removeItem(item) { - if (item === this._head && item === this._tail) { - this._head = undefined; - this._tail = undefined; - } - else if (item === this._head) { - this._head = item.next; - } - else if (item === this._tail) { - this._tail = item.previous; - } - else { - const next = item.next; - const previous = item.previous; - if (!next || !previous) { - throw new Error('Invalid list'); - } - next.previous = previous; - previous.next = next; - } - } - touch(item, touch) { - if (!this._head || !this._tail) { - throw new Error('Invalid list'); - } - if ((touch !== Touch.First && touch !== Touch.Last)) { - return; - } - if (touch === Touch.First) { - if (item === this._head) { - return; - } - const next = item.next; - const previous = item.previous; - // Unlink the item - if (item === this._tail) { - // previous must be defined since item was not head but is tail - // So there are more than on item in the map - previous.next = undefined; - this._tail = previous; - } - else { - // Both next and previous are not undefined since item was neither head nor tail. - next.previous = previous; - previous.next = next; - } - // Insert the node at head - item.previous = undefined; - item.next = this._head; - this._head.previous = item; - this._head = item; - } - else if (touch === Touch.Last) { - if (item === this._tail) { - return; - } - const next = item.next; - const previous = item.previous; - // Unlink the item. - if (item === this._head) { - // next must be defined since item was not tail but is head - // So there are more than on item in the map - next.previous = undefined; - this._head = next; - } - else { - // Both next and previous are not undefined since item was neither head nor tail. - next.previous = previous; - previous.next = next; - } - item.next = undefined; - item.previous = this._tail; - this._tail.next = item; - this._tail = item; - } - } -} -exports.LinkedMap = LinkedMap; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const path_1 = __webpack_require__(82); -const os_1 = __webpack_require__(76); -const crypto_1 = __webpack_require__(221); -const net_1 = __webpack_require__(157); -const messageReader_1 = __webpack_require__(215); -const messageWriter_1 = __webpack_require__(217); -function generateRandomPipeName() { - const randomSuffix = crypto_1.randomBytes(21).toString('hex'); - if (process.platform === 'win32') { - return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`; - } - else { - // Mac/Unix: use socket file - return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`); - } -} -exports.generateRandomPipeName = generateRandomPipeName; -function createClientPipeTransport(pipeName, encoding = 'utf-8') { - let connectResolve; - let connected = new Promise((resolve, _reject) => { - connectResolve = resolve; - }); - return new Promise((resolve, reject) => { - let server = net_1.createServer((socket) => { - server.close(); - connectResolve([ - new messageReader_1.SocketMessageReader(socket, encoding), - new messageWriter_1.SocketMessageWriter(socket, encoding) - ]); - }); - server.on('error', reject); - server.listen(pipeName, () => { - server.removeListener('error', reject); - resolve({ - onConnected: () => { return connected; } - }); - }); - }); -} -exports.createClientPipeTransport = createClientPipeTransport; -function createServerPipeTransport(pipeName, encoding = 'utf-8') { - const socket = net_1.createConnection(pipeName); - return [ - new messageReader_1.SocketMessageReader(socket, encoding), - new messageWriter_1.SocketMessageWriter(socket, encoding) - ]; -} -exports.createServerPipeTransport = createServerPipeTransport; - - -/***/ }), -/* 221 */ -/***/ (function(module, exports) { - -module.exports = require("crypto"); - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const net_1 = __webpack_require__(157); -const messageReader_1 = __webpack_require__(215); -const messageWriter_1 = __webpack_require__(217); -function createClientSocketTransport(port, encoding = 'utf-8') { - let connectResolve; - let connected = new Promise((resolve, _reject) => { - connectResolve = resolve; - }); - return new Promise((resolve, reject) => { - let server = net_1.createServer((socket) => { - server.close(); - connectResolve([ - new messageReader_1.SocketMessageReader(socket, encoding), - new messageWriter_1.SocketMessageWriter(socket, encoding) - ]); - }); - server.on('error', reject); - server.listen(port, '127.0.0.1', () => { - server.removeListener('error', reject); - resolve({ - onConnected: () => { return connected; } - }); - }); - }); -} -exports.createClientSocketTransport = createClientSocketTransport; -function createServerSocketTransport(port, encoding = 'utf-8') { - const socket = net_1.createConnection(port, '127.0.0.1'); - return [ - new messageReader_1.SocketMessageReader(socket, encoding), - new messageWriter_1.SocketMessageWriter(socket, encoding) - ]; -} -exports.createServerSocketTransport = createServerSocketTransport; - - -/***/ }), -/* 223 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; }); -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -/** - * The Position namespace provides helper functions to work with - * [Position](#Position) literals. - */ -var Position; -(function (Position) { - /** - * Creates a new Position literal from the given line and character. - * @param line The position's line. - * @param character The position's character. - */ - function create(line, character) { - return { line: line, character: character }; - } - Position.create = create; - /** - * Checks whether the given liternal conforms to the [Position](#Position) interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character); - } - Position.is = is; -})(Position || (Position = {})); -/** - * The Range namespace provides helper functions to work with - * [Range](#Range) literals. - */ -var Range; -(function (Range) { - function create(one, two, three, four) { - if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) { - return { start: Position.create(one, two), end: Position.create(three, four) }; - } - else if (Position.is(one) && Position.is(two)) { - return { start: one, end: two }; - } - else { - throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]"); - } - } - Range.create = create; - /** - * Checks whether the given literal conforms to the [Range](#Range) interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); - } - Range.is = is; -})(Range || (Range = {})); -/** - * The Location namespace provides helper functions to work with - * [Location](#Location) literals. - */ -var Location; -(function (Location) { - /** - * Creates a Location literal. - * @param uri The location's uri. - * @param range The location's range. - */ - function create(uri, range) { - return { uri: uri, range: range }; - } - Location.create = create; - /** - * Checks whether the given literal conforms to the [Location](#Location) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); - } - Location.is = is; -})(Location || (Location = {})); -/** - * The LocationLink namespace provides helper functions to work with - * [LocationLink](#LocationLink) literals. - */ -var LocationLink; -(function (LocationLink) { - /** - * Creates a LocationLink literal. - * @param targetUri The definition's uri. - * @param targetRange The full range of the definition. - * @param targetSelectionRange The span of the symbol definition at the target. - * @param originSelectionRange The span of the symbol being defined in the originating source file. - */ - function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { - return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange }; - } - LocationLink.create = create; - /** - * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) - && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange)) - && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); - } - LocationLink.is = is; -})(LocationLink || (LocationLink = {})); -/** - * The Color namespace provides helper functions to work with - * [Color](#Color) literals. - */ -var Color; -(function (Color) { - /** - * Creates a new Color literal. - */ - function create(red, green, blue, alpha) { - return { - red: red, - green: green, - blue: blue, - alpha: alpha, - }; - } - Color.create = create; - /** - * Checks whether the given literal conforms to the [Color](#Color) interface. - */ - function is(value) { - var candidate = value; - return Is.number(candidate.red) - && Is.number(candidate.green) - && Is.number(candidate.blue) - && Is.number(candidate.alpha); - } - Color.is = is; -})(Color || (Color = {})); -/** - * The ColorInformation namespace provides helper functions to work with - * [ColorInformation](#ColorInformation) literals. - */ -var ColorInformation; -(function (ColorInformation) { - /** - * Creates a new ColorInformation literal. - */ - function create(range, color) { - return { - range: range, - color: color, - }; - } - ColorInformation.create = create; - /** - * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface. - */ - function is(value) { - var candidate = value; - return Range.is(candidate.range) && Color.is(candidate.color); - } - ColorInformation.is = is; -})(ColorInformation || (ColorInformation = {})); -/** - * The Color namespace provides helper functions to work with - * [ColorPresentation](#ColorPresentation) literals. - */ -var ColorPresentation; -(function (ColorPresentation) { - /** - * Creates a new ColorInformation literal. - */ - function create(label, textEdit, additionalTextEdits) { - return { - label: label, - textEdit: textEdit, - additionalTextEdits: additionalTextEdits, - }; - } - ColorPresentation.create = create; - /** - * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface. - */ - function is(value) { - var candidate = value; - return Is.string(candidate.label) - && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) - && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); - } - ColorPresentation.is = is; -})(ColorPresentation || (ColorPresentation = {})); -/** - * Enum of known range kinds - */ -var FoldingRangeKind; -(function (FoldingRangeKind) { - /** - * Folding range for a comment - */ - FoldingRangeKind["Comment"] = "comment"; - /** - * Folding range for a imports or includes - */ - FoldingRangeKind["Imports"] = "imports"; - /** - * Folding range for a region (e.g. `#region`) - */ - FoldingRangeKind["Region"] = "region"; -})(FoldingRangeKind || (FoldingRangeKind = {})); -/** - * The folding range namespace provides helper functions to work with - * [FoldingRange](#FoldingRange) literals. - */ -var FoldingRange; -(function (FoldingRange) { - /** - * Creates a new FoldingRange literal. - */ - function create(startLine, endLine, startCharacter, endCharacter, kind) { - var result = { - startLine: startLine, - endLine: endLine - }; - if (Is.defined(startCharacter)) { - result.startCharacter = startCharacter; - } - if (Is.defined(endCharacter)) { - result.endCharacter = endCharacter; - } - if (Is.defined(kind)) { - result.kind = kind; - } - return result; - } - FoldingRange.create = create; - /** - * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface. - */ - function is(value) { - var candidate = value; - return Is.number(candidate.startLine) && Is.number(candidate.startLine) - && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter)) - && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter)) - && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); - } - FoldingRange.is = is; -})(FoldingRange || (FoldingRange = {})); -/** - * The DiagnosticRelatedInformation namespace provides helper functions to work with - * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals. - */ -var DiagnosticRelatedInformation; -(function (DiagnosticRelatedInformation) { - /** - * Creates a new DiagnosticRelatedInformation literal. - */ - function create(location, message) { - return { - location: location, - message: message - }; - } - DiagnosticRelatedInformation.create = create; - /** - * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); - } - DiagnosticRelatedInformation.is = is; -})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {})); -/** - * The diagnostic's severity. - */ -var DiagnosticSeverity; -(function (DiagnosticSeverity) { - /** - * Reports an error. - */ - DiagnosticSeverity.Error = 1; - /** - * Reports a warning. - */ - DiagnosticSeverity.Warning = 2; - /** - * Reports an information. - */ - DiagnosticSeverity.Information = 3; - /** - * Reports a hint. - */ - DiagnosticSeverity.Hint = 4; -})(DiagnosticSeverity || (DiagnosticSeverity = {})); -/** - * The diagnostic tags. - * - * @since 3.15.0 - */ -var DiagnosticTag; -(function (DiagnosticTag) { - /** - * Unused or unnecessary code. - * - * Clients are allowed to render diagnostics with this tag faded out instead of having - * an error squiggle. - */ - DiagnosticTag.Unnecessary = 1; - /** - * Deprecated or obsolete code. - * - * Clients are allowed to rendered diagnostics with this tag strike through. - */ - DiagnosticTag.Deprecated = 2; -})(DiagnosticTag || (DiagnosticTag = {})); -/** - * The Diagnostic namespace provides helper functions to work with - * [Diagnostic](#Diagnostic) literals. - */ -var Diagnostic; -(function (Diagnostic) { - /** - * Creates a new Diagnostic literal. - */ - function create(range, message, severity, code, source, relatedInformation) { - var result = { range: range, message: message }; - if (Is.defined(severity)) { - result.severity = severity; - } - if (Is.defined(code)) { - result.code = code; - } - if (Is.defined(source)) { - result.source = source; - } - if (Is.defined(relatedInformation)) { - result.relatedInformation = relatedInformation; - } - return result; - } - Diagnostic.create = create; - /** - * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) - && Range.is(candidate.range) - && Is.string(candidate.message) - && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) - && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) - && (Is.string(candidate.source) || Is.undefined(candidate.source)) - && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); - } - Diagnostic.is = is; -})(Diagnostic || (Diagnostic = {})); -/** - * The Command namespace provides helper functions to work with - * [Command](#Command) literals. - */ -var Command; -(function (Command) { - /** - * Creates a new Command literal. - */ - function create(title, command) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var result = { title: title, command: command }; - if (Is.defined(args) && args.length > 0) { - result.arguments = args; - } - return result; - } - Command.create = create; - /** - * Checks whether the given literal conforms to the [Command](#Command) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); - } - Command.is = is; -})(Command || (Command = {})); -/** - * The TextEdit namespace provides helper function to create replace, - * insert and delete edits more easily. - */ -var TextEdit; -(function (TextEdit) { - /** - * Creates a replace text edit. - * @param range The range of text to be replaced. - * @param newText The new text. - */ - function replace(range, newText) { - return { range: range, newText: newText }; - } - TextEdit.replace = replace; - /** - * Creates a insert text edit. - * @param position The position to insert the text at. - * @param newText The text to be inserted. - */ - function insert(position, newText) { - return { range: { start: position, end: position }, newText: newText }; - } - TextEdit.insert = insert; - /** - * Creates a delete text edit. - * @param range The range of text to be deleted. - */ - function del(range) { - return { range: range, newText: '' }; - } - TextEdit.del = del; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) - && Is.string(candidate.newText) - && Range.is(candidate.range); - } - TextEdit.is = is; -})(TextEdit || (TextEdit = {})); -/** - * The TextDocumentEdit namespace provides helper function to create - * an edit that manipulates a text document. - */ -var TextDocumentEdit; -(function (TextDocumentEdit) { - /** - * Creates a new `TextDocumentEdit` - */ - function create(textDocument, edits) { - return { textDocument: textDocument, edits: edits }; - } - TextDocumentEdit.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) - && VersionedTextDocumentIdentifier.is(candidate.textDocument) - && Array.isArray(candidate.edits); - } - TextDocumentEdit.is = is; -})(TextDocumentEdit || (TextDocumentEdit = {})); -var CreateFile; -(function (CreateFile) { - function create(uri, options) { - var result = { - kind: 'create', - uri: uri - }; - if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { - result.options = options; - } - return result; - } - CreateFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && - (candidate.options === void 0 || - ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)))); - } - CreateFile.is = is; -})(CreateFile || (CreateFile = {})); -var RenameFile; -(function (RenameFile) { - function create(oldUri, newUri, options) { - var result = { - kind: 'rename', - oldUri: oldUri, - newUri: newUri - }; - if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { - result.options = options; - } - return result; - } - RenameFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && - (candidate.options === void 0 || - ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)))); - } - RenameFile.is = is; -})(RenameFile || (RenameFile = {})); -var DeleteFile; -(function (DeleteFile) { - function create(uri, options) { - var result = { - kind: 'delete', - uri: uri - }; - if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) { - result.options = options; - } - return result; - } - DeleteFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && - (candidate.options === void 0 || - ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists)))); - } - DeleteFile.is = is; -})(DeleteFile || (DeleteFile = {})); -var WorkspaceEdit; -(function (WorkspaceEdit) { - function is(value) { - var candidate = value; - return candidate && - (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && - (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) { - if (Is.string(change.kind)) { - return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); - } - else { - return TextDocumentEdit.is(change); - } - })); - } - WorkspaceEdit.is = is; -})(WorkspaceEdit || (WorkspaceEdit = {})); -var TextEditChangeImpl = /** @class */ (function () { - function TextEditChangeImpl(edits) { - this.edits = edits; - } - TextEditChangeImpl.prototype.insert = function (position, newText) { - this.edits.push(TextEdit.insert(position, newText)); - }; - TextEditChangeImpl.prototype.replace = function (range, newText) { - this.edits.push(TextEdit.replace(range, newText)); - }; - TextEditChangeImpl.prototype.delete = function (range) { - this.edits.push(TextEdit.del(range)); - }; - TextEditChangeImpl.prototype.add = function (edit) { - this.edits.push(edit); - }; - TextEditChangeImpl.prototype.all = function () { - return this.edits; - }; - TextEditChangeImpl.prototype.clear = function () { - this.edits.splice(0, this.edits.length); - }; - return TextEditChangeImpl; -}()); -/** - * A workspace change helps constructing changes to a workspace. - */ -var WorkspaceChange = /** @class */ (function () { - function WorkspaceChange(workspaceEdit) { - var _this = this; - this._textEditChanges = Object.create(null); - if (workspaceEdit) { - this._workspaceEdit = workspaceEdit; - if (workspaceEdit.documentChanges) { - workspaceEdit.documentChanges.forEach(function (change) { - if (TextDocumentEdit.is(change)) { - var textEditChange = new TextEditChangeImpl(change.edits); - _this._textEditChanges[change.textDocument.uri] = textEditChange; - } - }); - } - else if (workspaceEdit.changes) { - Object.keys(workspaceEdit.changes).forEach(function (key) { - var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); - _this._textEditChanges[key] = textEditChange; - }); - } - } - } - Object.defineProperty(WorkspaceChange.prototype, "edit", { - /** - * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal - * use to be returned from a workspace edit operation like rename. - */ - get: function () { - return this._workspaceEdit; - }, - enumerable: true, - configurable: true - }); - WorkspaceChange.prototype.getTextEditChange = function (key) { - if (VersionedTextDocumentIdentifier.is(key)) { - if (!this._workspaceEdit) { - this._workspaceEdit = { - documentChanges: [] - }; - } - if (!this._workspaceEdit.documentChanges) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var textDocument = key; - var result = this._textEditChanges[textDocument.uri]; - if (!result) { - var edits = []; - var textDocumentEdit = { - textDocument: textDocument, - edits: edits - }; - this._workspaceEdit.documentChanges.push(textDocumentEdit); - result = new TextEditChangeImpl(edits); - this._textEditChanges[textDocument.uri] = result; - } - return result; - } - else { - if (!this._workspaceEdit) { - this._workspaceEdit = { - changes: Object.create(null) - }; - } - if (!this._workspaceEdit.changes) { - throw new Error('Workspace edit is not configured for normal text edit changes.'); - } - var result = this._textEditChanges[key]; - if (!result) { - var edits = []; - this._workspaceEdit.changes[key] = edits; - result = new TextEditChangeImpl(edits); - this._textEditChanges[key] = result; - } - return result; - } - }; - WorkspaceChange.prototype.createFile = function (uri, options) { - this.checkDocumentChanges(); - this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options)); - }; - WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) { - this.checkDocumentChanges(); - this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options)); - }; - WorkspaceChange.prototype.deleteFile = function (uri, options) { - this.checkDocumentChanges(); - this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options)); - }; - WorkspaceChange.prototype.checkDocumentChanges = function () { - if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) { - throw new Error('Workspace edit is not configured for document changes.'); - } - }; - return WorkspaceChange; -}()); - -/** - * The TextDocumentIdentifier namespace provides helper functions to work with - * [TextDocumentIdentifier](#TextDocumentIdentifier) literals. - */ -var TextDocumentIdentifier; -(function (TextDocumentIdentifier) { - /** - * Creates a new TextDocumentIdentifier literal. - * @param uri The document's uri. - */ - function create(uri) { - return { uri: uri }; - } - TextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri); - } - TextDocumentIdentifier.is = is; -})(TextDocumentIdentifier || (TextDocumentIdentifier = {})); -/** - * The VersionedTextDocumentIdentifier namespace provides helper functions to work with - * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals. - */ -var VersionedTextDocumentIdentifier; -(function (VersionedTextDocumentIdentifier) { - /** - * Creates a new VersionedTextDocumentIdentifier literal. - * @param uri The document's uri. - * @param uri The document's text. - */ - function create(uri, version) { - return { uri: uri, version: version }; - } - VersionedTextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version)); - } - VersionedTextDocumentIdentifier.is = is; -})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {})); -/** - * The TextDocumentItem namespace provides helper functions to work with - * [TextDocumentItem](#TextDocumentItem) literals. - */ -var TextDocumentItem; -(function (TextDocumentItem) { - /** - * Creates a new TextDocumentItem literal. - * @param uri The document's uri. - * @param languageId The document's language identifier. - * @param version The document's version number. - * @param text The document's text. - */ - function create(uri, languageId, version, text) { - return { uri: uri, languageId: languageId, version: version, text: text }; - } - TextDocumentItem.create = create; - /** - * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text); - } - TextDocumentItem.is = is; -})(TextDocumentItem || (TextDocumentItem = {})); -/** - * Describes the content type that a client supports in various - * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. - * - * Please note that `MarkupKinds` must not start with a `$`. This kinds - * are reserved for internal usage. - */ -var MarkupKind; -(function (MarkupKind) { - /** - * Plain text is supported as a content format - */ - MarkupKind.PlainText = 'plaintext'; - /** - * Markdown is supported as a content format - */ - MarkupKind.Markdown = 'markdown'; -})(MarkupKind || (MarkupKind = {})); -(function (MarkupKind) { - /** - * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type. - */ - function is(value) { - var candidate = value; - return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; - } - MarkupKind.is = is; -})(MarkupKind || (MarkupKind = {})); -var MarkupContent; -(function (MarkupContent) { - /** - * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); - } - MarkupContent.is = is; -})(MarkupContent || (MarkupContent = {})); -/** - * The kind of a completion entry. - */ -var CompletionItemKind; -(function (CompletionItemKind) { - CompletionItemKind.Text = 1; - CompletionItemKind.Method = 2; - CompletionItemKind.Function = 3; - CompletionItemKind.Constructor = 4; - CompletionItemKind.Field = 5; - CompletionItemKind.Variable = 6; - CompletionItemKind.Class = 7; - CompletionItemKind.Interface = 8; - CompletionItemKind.Module = 9; - CompletionItemKind.Property = 10; - CompletionItemKind.Unit = 11; - CompletionItemKind.Value = 12; - CompletionItemKind.Enum = 13; - CompletionItemKind.Keyword = 14; - CompletionItemKind.Snippet = 15; - CompletionItemKind.Color = 16; - CompletionItemKind.File = 17; - CompletionItemKind.Reference = 18; - CompletionItemKind.Folder = 19; - CompletionItemKind.EnumMember = 20; - CompletionItemKind.Constant = 21; - CompletionItemKind.Struct = 22; - CompletionItemKind.Event = 23; - CompletionItemKind.Operator = 24; - CompletionItemKind.TypeParameter = 25; -})(CompletionItemKind || (CompletionItemKind = {})); -/** - * Defines whether the insert text in a completion item should be interpreted as - * plain text or a snippet. - */ -var InsertTextFormat; -(function (InsertTextFormat) { - /** - * The primary text to be inserted is treated as a plain string. - */ - InsertTextFormat.PlainText = 1; - /** - * The primary text to be inserted is treated as a snippet. - * - * A snippet can define tab stops and placeholders with `$1`, `$2` - * and `${3:foo}`. `$0` defines the final tab stop, it defaults to - * the end of the snippet. Placeholders with equal identifiers are linked, - * that is typing in one will update others too. - * - * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md - */ - InsertTextFormat.Snippet = 2; -})(InsertTextFormat || (InsertTextFormat = {})); -/** - * Completion item tags are extra annotations that tweak the rendering of a completion - * item. - * - * @since 3.15.0 - */ -var CompletionItemTag; -(function (CompletionItemTag) { - /** - * Render a completion as obsolete, usually using a strike-out. - */ - CompletionItemTag.Deprecated = 1; -})(CompletionItemTag || (CompletionItemTag = {})); -/** - * The CompletionItem namespace provides functions to deal with - * completion items. - */ -var CompletionItem; -(function (CompletionItem) { - /** - * Create a completion item and seed it with a label. - * @param label The completion item's label - */ - function create(label) { - return { label: label }; - } - CompletionItem.create = create; -})(CompletionItem || (CompletionItem = {})); -/** - * The CompletionList namespace provides functions to deal with - * completion lists. - */ -var CompletionList; -(function (CompletionList) { - /** - * Creates a new completion list. - * - * @param items The completion items. - * @param isIncomplete The list is not complete. - */ - function create(items, isIncomplete) { - return { items: items ? items : [], isIncomplete: !!isIncomplete }; - } - CompletionList.create = create; -})(CompletionList || (CompletionList = {})); -var MarkedString; -(function (MarkedString) { - /** - * Creates a marked string from plain text. - * - * @param plainText The plain text. - */ - function fromPlainText(plainText) { - return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash - } - MarkedString.fromPlainText = fromPlainText; - /** - * Checks whether the given value conforms to the [MarkedString](#MarkedString) type. - */ - function is(value) { - var candidate = value; - return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value)); - } - MarkedString.is = is; -})(MarkedString || (MarkedString = {})); -var Hover; -(function (Hover) { - /** - * Checks whether the given value conforms to the [Hover](#Hover) interface. - */ - function is(value) { - var candidate = value; - return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || - MarkedString.is(candidate.contents) || - Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range)); - } - Hover.is = is; -})(Hover || (Hover = {})); -/** - * The ParameterInformation namespace provides helper functions to work with - * [ParameterInformation](#ParameterInformation) literals. - */ -var ParameterInformation; -(function (ParameterInformation) { - /** - * Creates a new parameter information literal. - * - * @param label A label string. - * @param documentation A doc string. - */ - function create(label, documentation) { - return documentation ? { label: label, documentation: documentation } : { label: label }; - } - ParameterInformation.create = create; -})(ParameterInformation || (ParameterInformation = {})); -/** - * The SignatureInformation namespace provides helper functions to work with - * [SignatureInformation](#SignatureInformation) literals. - */ -var SignatureInformation; -(function (SignatureInformation) { - function create(label, documentation) { - var parameters = []; - for (var _i = 2; _i < arguments.length; _i++) { - parameters[_i - 2] = arguments[_i]; - } - var result = { label: label }; - if (Is.defined(documentation)) { - result.documentation = documentation; - } - if (Is.defined(parameters)) { - result.parameters = parameters; - } - else { - result.parameters = []; - } - return result; - } - SignatureInformation.create = create; -})(SignatureInformation || (SignatureInformation = {})); -/** - * A document highlight kind. - */ -var DocumentHighlightKind; -(function (DocumentHighlightKind) { - /** - * A textual occurrence. - */ - DocumentHighlightKind.Text = 1; - /** - * Read-access of a symbol, like reading a variable. - */ - DocumentHighlightKind.Read = 2; - /** - * Write-access of a symbol, like writing to a variable. - */ - DocumentHighlightKind.Write = 3; -})(DocumentHighlightKind || (DocumentHighlightKind = {})); -/** - * DocumentHighlight namespace to provide helper functions to work with - * [DocumentHighlight](#DocumentHighlight) literals. - */ -var DocumentHighlight; -(function (DocumentHighlight) { - /** - * Create a DocumentHighlight object. - * @param range The range the highlight applies to. - */ - function create(range, kind) { - var result = { range: range }; - if (Is.number(kind)) { - result.kind = kind; - } - return result; - } - DocumentHighlight.create = create; -})(DocumentHighlight || (DocumentHighlight = {})); -/** - * A symbol kind. - */ -var SymbolKind; -(function (SymbolKind) { - SymbolKind.File = 1; - SymbolKind.Module = 2; - SymbolKind.Namespace = 3; - SymbolKind.Package = 4; - SymbolKind.Class = 5; - SymbolKind.Method = 6; - SymbolKind.Property = 7; - SymbolKind.Field = 8; - SymbolKind.Constructor = 9; - SymbolKind.Enum = 10; - SymbolKind.Interface = 11; - SymbolKind.Function = 12; - SymbolKind.Variable = 13; - SymbolKind.Constant = 14; - SymbolKind.String = 15; - SymbolKind.Number = 16; - SymbolKind.Boolean = 17; - SymbolKind.Array = 18; - SymbolKind.Object = 19; - SymbolKind.Key = 20; - SymbolKind.Null = 21; - SymbolKind.EnumMember = 22; - SymbolKind.Struct = 23; - SymbolKind.Event = 24; - SymbolKind.Operator = 25; - SymbolKind.TypeParameter = 26; -})(SymbolKind || (SymbolKind = {})); -/** - * Symbol tags are extra annotations that tweak the rendering of a symbol. - * @since 3.15 - */ -var SymbolTag; -(function (SymbolTag) { - /** - * Render a symbol as obsolete, usually using a strike-out. - */ - SymbolTag.Deprecated = 1; -})(SymbolTag || (SymbolTag = {})); -var SymbolInformation; -(function (SymbolInformation) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the location of the symbol. - * @param uri The resource of the location of symbol, defaults to the current document. - * @param containerName The name of the symbol containing the symbol. - */ - function create(name, kind, range, uri, containerName) { - var result = { - name: name, - kind: kind, - location: { uri: uri, range: range } - }; - if (containerName) { - result.containerName = containerName; - } - return result; - } - SymbolInformation.create = create; -})(SymbolInformation || (SymbolInformation = {})); -var DocumentSymbol; -(function (DocumentSymbol) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param detail The detail of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the symbol. - * @param selectionRange The selectionRange of the symbol. - * @param children Children of the symbol. - */ - function create(name, detail, kind, range, selectionRange, children) { - var result = { - name: name, - detail: detail, - kind: kind, - range: range, - selectionRange: selectionRange - }; - if (children !== void 0) { - result.children = children; - } - return result; - } - DocumentSymbol.create = create; - /** - * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface. - */ - function is(value) { - var candidate = value; - return candidate && - Is.string(candidate.name) && Is.number(candidate.kind) && - Range.is(candidate.range) && Range.is(candidate.selectionRange) && - (candidate.detail === void 0 || Is.string(candidate.detail)) && - (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && - (candidate.children === void 0 || Array.isArray(candidate.children)); - } - DocumentSymbol.is = is; -})(DocumentSymbol || (DocumentSymbol = {})); -/** - * A set of predefined code action kinds - */ -var CodeActionKind; -(function (CodeActionKind) { - /** - * Empty kind. - */ - CodeActionKind.Empty = ''; - /** - * Base kind for quickfix actions: 'quickfix' - */ - CodeActionKind.QuickFix = 'quickfix'; - /** - * Base kind for refactoring actions: 'refactor' - */ - CodeActionKind.Refactor = 'refactor'; - /** - * Base kind for refactoring extraction actions: 'refactor.extract' - * - * Example extract actions: - * - * - Extract method - * - Extract function - * - Extract variable - * - Extract interface from class - * - ... - */ - CodeActionKind.RefactorExtract = 'refactor.extract'; - /** - * Base kind for refactoring inline actions: 'refactor.inline' - * - * Example inline actions: - * - * - Inline function - * - Inline variable - * - Inline constant - * - ... - */ - CodeActionKind.RefactorInline = 'refactor.inline'; - /** - * Base kind for refactoring rewrite actions: 'refactor.rewrite' - * - * Example rewrite actions: - * - * - Convert JavaScript function to class - * - Add or remove parameter - * - Encapsulate field - * - Make method static - * - Move method to base class - * - ... - */ - CodeActionKind.RefactorRewrite = 'refactor.rewrite'; - /** - * Base kind for source actions: `source` - * - * Source code actions apply to the entire file. - */ - CodeActionKind.Source = 'source'; - /** - * Base kind for an organize imports source action: `source.organizeImports` - */ - CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; - /** - * Base kind for auto-fix source actions: `source.fixAll`. - * - * Fix all actions automatically fix errors that have a clear fix that do not require user input. - * They should not suppress errors or perform unsafe fixes such as generating new types or classes. - * - * @since 3.15.0 - */ - CodeActionKind.SourceFixAll = 'source.fixAll'; -})(CodeActionKind || (CodeActionKind = {})); -/** - * The CodeActionContext namespace provides helper functions to work with - * [CodeActionContext](#CodeActionContext) literals. - */ -var CodeActionContext; -(function (CodeActionContext) { - /** - * Creates a new CodeActionContext literal. - */ - function create(diagnostics, only) { - var result = { diagnostics: diagnostics }; - if (only !== void 0 && only !== null) { - result.only = only; - } - return result; - } - CodeActionContext.create = create; - /** - * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)); - } - CodeActionContext.is = is; -})(CodeActionContext || (CodeActionContext = {})); -var CodeAction; -(function (CodeAction) { - function create(title, commandOrEdit, kind) { - var result = { title: title }; - if (Command.is(commandOrEdit)) { - result.command = commandOrEdit; - } - else { - result.edit = commandOrEdit; - } - if (kind !== void 0) { - result.kind = kind; - } - return result; - } - CodeAction.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.title) && - (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && - (candidate.kind === void 0 || Is.string(candidate.kind)) && - (candidate.edit !== void 0 || candidate.command !== void 0) && - (candidate.command === void 0 || Command.is(candidate.command)) && - (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && - (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit)); - } - CodeAction.is = is; -})(CodeAction || (CodeAction = {})); -/** - * The CodeLens namespace provides helper functions to work with - * [CodeLens](#CodeLens) literals. - */ -var CodeLens; -(function (CodeLens) { - /** - * Creates a new CodeLens literal. - */ - function create(range, data) { - var result = { range: range }; - if (Is.defined(data)) { - result.data = data; - } - return result; - } - CodeLens.create = create; - /** - * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); - } - CodeLens.is = is; -})(CodeLens || (CodeLens = {})); -/** - * The FormattingOptions namespace provides helper functions to work with - * [FormattingOptions](#FormattingOptions) literals. - */ -var FormattingOptions; -(function (FormattingOptions) { - /** - * Creates a new FormattingOptions literal. - */ - function create(tabSize, insertSpaces) { - return { tabSize: tabSize, insertSpaces: insertSpaces }; - } - FormattingOptions.create = create; - /** - * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces); - } - FormattingOptions.is = is; -})(FormattingOptions || (FormattingOptions = {})); -/** - * The DocumentLink namespace provides helper functions to work with - * [DocumentLink](#DocumentLink) literals. - */ -var DocumentLink; -(function (DocumentLink) { - /** - * Creates a new DocumentLink literal. - */ - function create(range, target, data) { - return { range: range, target: target, data: data }; - } - DocumentLink.create = create; - /** - * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); - } - DocumentLink.is = is; -})(DocumentLink || (DocumentLink = {})); -/** - * The SelectionRange namespace provides helper function to work with - * SelectionRange literals. - */ -var SelectionRange; -(function (SelectionRange) { - /** - * Creates a new SelectionRange - * @param range the range. - * @param parent an optional parent. - */ - function create(range, parent) { - return { range: range, parent: parent }; - } - SelectionRange.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); - } - SelectionRange.is = is; -})(SelectionRange || (SelectionRange = {})); -var EOL = ['\n', '\r\n', '\r']; -/** - * @deprecated Use the text document from the new vscode-languageserver-textdocument package. - */ -var TextDocument; -(function (TextDocument) { - /** - * Creates a new ITextDocument literal from the given uri and content. - * @param uri The document's uri. - * @param languageId The document's language Id. - * @param content The document's content. - */ - function create(uri, languageId, version, content) { - return new FullTextDocument(uri, languageId, version, content); - } - TextDocument.create = create; - /** - * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount) - && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; - } - TextDocument.is = is; - function applyEdits(document, edits) { - var text = document.getText(); - var sortedEdits = mergeSort(edits, function (a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = text.length; - for (var i = sortedEdits.length - 1; i >= 0; i--) { - var e = sortedEdits[i]; - var startOffset = document.offsetAt(e.range.start); - var endOffset = document.offsetAt(e.range.end); - if (endOffset <= lastModifiedOffset) { - text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); - } - else { - throw new Error('Overlapping edit'); - } - lastModifiedOffset = startOffset; - } - return text; - } - TextDocument.applyEdits = applyEdits; - function mergeSort(data, compare) { - if (data.length <= 1) { - // sorted - return data; - } - var p = (data.length / 2) | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort(left, compare); - mergeSort(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - // smaller_equal -> take left to preserve order - data[i++] = left[leftIdx++]; - } - else { - // greater -> take right - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; - } -})(TextDocument || (TextDocument = {})); -var FullTextDocument = /** @class */ (function () { - function FullTextDocument(uri, languageId, version, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version; - this._content = content; - this._lineOffsets = undefined; - } - Object.defineProperty(FullTextDocument.prototype, "uri", { - get: function () { - return this._uri; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "languageId", { - get: function () { - return this._languageId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "version", { - get: function () { - return this._version; - }, - enumerable: true, - configurable: true - }); - FullTextDocument.prototype.getText = function (range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument.prototype.update = function (event, version) { - this._content = event.text; - this._version = version; - this._lineOffsets = undefined; - }; - FullTextDocument.prototype.getLineOffsets = function () { - if (this._lineOffsets === undefined) { - var lineOffsets = []; - var text = this._content; - var isLineStart = true; - for (var i = 0; i < text.length; i++) { - if (isLineStart) { - lineOffsets.push(i); - isLineStart = false; - } - var ch = text.charAt(i); - isLineStart = (ch === '\r' || ch === '\n'); - if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { - i++; - } - } - if (isLineStart && text.length > 0) { - lineOffsets.push(text.length); - } - this._lineOffsets = lineOffsets; - } - return this._lineOffsets; - }; - FullTextDocument.prototype.positionAt = function (offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, high = lineOffsets.length; - if (high === 0) { - return Position.create(0, offset); - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } - else { - low = mid + 1; - } - } - // low is the least x for which the line offset is larger than the current offset - // or array.length if no line offset is larger than the current offset - var line = low - 1; - return Position.create(line, offset - lineOffsets[line]); - }; - FullTextDocument.prototype.offsetAt = function (position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } - else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument.prototype, "lineCount", { - get: function () { - return this.getLineOffsets().length; - }, - enumerable: true, - configurable: true - }); - return FullTextDocument; -}()); -var Is; -(function (Is) { - var toString = Object.prototype.toString; - function defined(value) { - return typeof value !== 'undefined'; - } - Is.defined = defined; - function undefined(value) { - return typeof value === 'undefined'; - } - Is.undefined = undefined; - function boolean(value) { - return value === true || value === false; - } - Is.boolean = boolean; - function string(value) { - return toString.call(value) === '[object String]'; - } - Is.string = string; - function number(value) { - return toString.call(value) === '[object Number]'; - } - Is.number = number; - function func(value) { - return toString.call(value) === '[object Function]'; - } - Is.func = func; - function objectLiteral(value) { - // Strictly speaking class instances pass this check as well. Since the LSP - // doesn't use classes we ignore this for now. If we do we need to add something - // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` - return value !== null && typeof value === 'object'; - } - Is.objectLiteral = objectLiteral; - function typedArray(value, check) { - return Array.isArray(value) && value.every(check); - } - Is.typedArray = typedArray; -})(Is || (Is = {})); - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const Is = __webpack_require__(225); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -const protocol_implementation_1 = __webpack_require__(227); -exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest; -const protocol_typeDefinition_1 = __webpack_require__(228); -exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest; -const protocol_workspaceFolders_1 = __webpack_require__(229); -exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest; -exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification; -const protocol_configuration_1 = __webpack_require__(230); -exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest; -const protocol_colorProvider_1 = __webpack_require__(231); -exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest; -exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest; -const protocol_foldingRange_1 = __webpack_require__(232); -exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest; -const protocol_declaration_1 = __webpack_require__(233); -exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest; -const protocol_selectionRange_1 = __webpack_require__(234); -exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest; -const protocol_progress_1 = __webpack_require__(235); -exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress; -exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest; -exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification; -// @ts-ignore: to avoid inlining LocatioLink as dynamic import -let __noDynamicImport; -/** - * The DocumentFilter namespace provides helper functions to work with - * [DocumentFilter](#DocumentFilter) literals. - */ -var DocumentFilter; -(function (DocumentFilter) { - function is(value) { - const candidate = value; - return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern); - } - DocumentFilter.is = is; -})(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {})); -/** - * The DocumentSelector namespace provides helper functions to work with - * [DocumentSelector](#DocumentSelector)s. - */ -var DocumentSelector; -(function (DocumentSelector) { - function is(value) { - if (!Array.isArray(value)) { - return false; - } - for (let elem of value) { - if (!Is.string(elem) && !DocumentFilter.is(elem)) { - return false; - } - } - return true; - } - DocumentSelector.is = is; -})(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {})); -/** - * The `client/registerCapability` request is sent from the server to the client to register a new capability - * handler on the client side. - */ -var RegistrationRequest; -(function (RegistrationRequest) { - RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability'); -})(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {})); -/** - * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability - * handler on the client side. - */ -var UnregistrationRequest; -(function (UnregistrationRequest) { - UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability'); -})(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {})); -var ResourceOperationKind; -(function (ResourceOperationKind) { - /** - * Supports creating new files and folders. - */ - ResourceOperationKind.Create = 'create'; - /** - * Supports renaming existing files and folders. - */ - ResourceOperationKind.Rename = 'rename'; - /** - * Supports deleting existing files and folders. - */ - ResourceOperationKind.Delete = 'delete'; -})(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {})); -var FailureHandlingKind; -(function (FailureHandlingKind) { - /** - * Applying the workspace change is simply aborted if one of the changes provided - * fails. All operations executed before the failing operation stay executed. - */ - FailureHandlingKind.Abort = 'abort'; - /** - * All operations are executed transactional. That means they either all - * succeed or no changes at all are applied to the workspace. - */ - FailureHandlingKind.Transactional = 'transactional'; - /** - * If the workspace edit contains only textual file changes they are executed transactional. - * If resource changes (create, rename or delete file) are part of the change the failure - * handling startegy is abort. - */ - FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional'; - /** - * The client tries to undo the operations already executed. But there is no - * guarantee that this is succeeding. - */ - FailureHandlingKind.Undo = 'undo'; -})(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {})); -/** - * The StaticRegistrationOptions namespace provides helper functions to work with - * [StaticRegistrationOptions](#StaticRegistrationOptions) literals. - */ -var StaticRegistrationOptions; -(function (StaticRegistrationOptions) { - function hasId(value) { - const candidate = value; - return candidate && Is.string(candidate.id) && candidate.id.length > 0; - } - StaticRegistrationOptions.hasId = hasId; -})(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {})); -/** - * The TextDocumentRegistrationOptions namespace provides helper functions to work with - * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals. - */ -var TextDocumentRegistrationOptions; -(function (TextDocumentRegistrationOptions) { - function is(value) { - const candidate = value; - return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector)); - } - TextDocumentRegistrationOptions.is = is; -})(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {})); -/** - * The WorkDoneProgressOptions namespace provides helper functions to work with - * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals. - */ -var WorkDoneProgressOptions; -(function (WorkDoneProgressOptions) { - function is(value) { - const candidate = value; - return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress)); - } - WorkDoneProgressOptions.is = is; - function hasWorkDoneProgress(value) { - const candidate = value; - return candidate && Is.boolean(candidate.workDoneProgress); - } - WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress; -})(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {})); -/** - * The initialize request is sent from the client to the server. - * It is sent once as the request after starting up the server. - * The requests parameter is of type [InitializeParams](#InitializeParams) - * the response if of type [InitializeResult](#InitializeResult) of a Thenable that - * resolves to such. - */ -var InitializeRequest; -(function (InitializeRequest) { - InitializeRequest.type = new messages_1.ProtocolRequestType('initialize'); -})(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {})); -/** - * Known error codes for an `InitializeError`; - */ -var InitializeError; -(function (InitializeError) { - /** - * If the protocol version provided by the client can't be handled by the server. - * @deprecated This initialize error got replaced by client capabilities. There is - * no version handshake in version 3.0x - */ - InitializeError.unknownProtocolVersion = 1; -})(InitializeError = exports.InitializeError || (exports.InitializeError = {})); -/** - * The intialized notification is sent from the client to the - * server after the client is fully initialized and the server - * is allowed to send requests from the server to the client. - */ -var InitializedNotification; -(function (InitializedNotification) { - InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized'); -})(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {})); -//---- Shutdown Method ---- -/** - * A shutdown request is sent from the client to the server. - * It is sent once when the client decides to shutdown the - * server. The only notification that is sent after a shutdown request - * is the exit event. - */ -var ShutdownRequest; -(function (ShutdownRequest) { - ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown'); -})(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {})); -//---- Exit Notification ---- -/** - * The exit event is sent from the client to the server to - * ask the server to exit its process. - */ -var ExitNotification; -(function (ExitNotification) { - ExitNotification.type = new messages_1.ProtocolNotificationType0('exit'); -})(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {})); -/** - * The configuration change notification is sent from the client to the server - * when the client's configuration has changed. The notification contains - * the changed configuration as defined by the language client. - */ -var DidChangeConfigurationNotification; -(function (DidChangeConfigurationNotification) { - DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration'); -})(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {})); -//---- Message show and log notifications ---- -/** - * The message type - */ -var MessageType; -(function (MessageType) { - /** - * An error message. - */ - MessageType.Error = 1; - /** - * A warning message. - */ - MessageType.Warning = 2; - /** - * An information message. - */ - MessageType.Info = 3; - /** - * A log message. - */ - MessageType.Log = 4; -})(MessageType = exports.MessageType || (exports.MessageType = {})); -/** - * The show message notification is sent from a server to a client to ask - * the client to display a particular message in the user interface. - */ -var ShowMessageNotification; -(function (ShowMessageNotification) { - ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage'); -})(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {})); -/** - * The show message request is sent from the server to the client to show a message - * and a set of options actions to the user. - */ -var ShowMessageRequest; -(function (ShowMessageRequest) { - ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest'); -})(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {})); -/** - * The log message notification is sent from the server to the client to ask - * the client to log a particular message. - */ -var LogMessageNotification; -(function (LogMessageNotification) { - LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage'); -})(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {})); -//---- Telemetry notification -/** - * The telemetry event notification is sent from the server to the client to ask - * the client to log telemetry data. - */ -var TelemetryEventNotification; -(function (TelemetryEventNotification) { - TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event'); -})(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {})); -/** - * Defines how the host (editor) should sync - * document changes to the language server. - */ -var TextDocumentSyncKind; -(function (TextDocumentSyncKind) { - /** - * Documents should not be synced at all. - */ - TextDocumentSyncKind.None = 0; - /** - * Documents are synced by always sending the full content - * of the document. - */ - TextDocumentSyncKind.Full = 1; - /** - * Documents are synced by sending the full content on open. - * After that only incremental updates to the document are - * send. - */ - TextDocumentSyncKind.Incremental = 2; -})(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {})); -/** - * The document open notification is sent from the client to the server to signal - * newly opened text documents. The document's truth is now managed by the client - * and the server must not try to read the document's truth using the document's - * uri. Open in this sense means it is managed by the client. It doesn't necessarily - * mean that its content is presented in an editor. An open notification must not - * be sent more than once without a corresponding close notification send before. - * This means open and close notification must be balanced and the max open count - * is one. - */ -var DidOpenTextDocumentNotification; -(function (DidOpenTextDocumentNotification) { - DidOpenTextDocumentNotification.method = 'textDocument/didOpen'; - DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method); -})(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {})); -/** - * The document change notification is sent from the client to the server to signal - * changes to a text document. - */ -var DidChangeTextDocumentNotification; -(function (DidChangeTextDocumentNotification) { - DidChangeTextDocumentNotification.method = 'textDocument/didChange'; - DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method); -})(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {})); -/** - * The document close notification is sent from the client to the server when - * the document got closed in the client. The document's truth now exists where - * the document's uri points to (e.g. if the document's uri is a file uri the - * truth now exists on disk). As with the open notification the close notification - * is about managing the document's content. Receiving a close notification - * doesn't mean that the document was open in an editor before. A close - * notification requires a previous open notification to be sent. - */ -var DidCloseTextDocumentNotification; -(function (DidCloseTextDocumentNotification) { - DidCloseTextDocumentNotification.method = 'textDocument/didClose'; - DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method); -})(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {})); -/** - * The document save notification is sent from the client to the server when - * the document got saved in the client. - */ -var DidSaveTextDocumentNotification; -(function (DidSaveTextDocumentNotification) { - DidSaveTextDocumentNotification.method = 'textDocument/didSave'; - DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method); -})(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {})); -/** - * Represents reasons why a text document is saved. - */ -var TextDocumentSaveReason; -(function (TextDocumentSaveReason) { - /** - * Manually triggered, e.g. by the user pressing save, by starting debugging, - * or by an API call. - */ - TextDocumentSaveReason.Manual = 1; - /** - * Automatic after a delay. - */ - TextDocumentSaveReason.AfterDelay = 2; - /** - * When the editor lost focus. - */ - TextDocumentSaveReason.FocusOut = 3; -})(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {})); -/** - * A document will save notification is sent from the client to the server before - * the document is actually saved. - */ -var WillSaveTextDocumentNotification; -(function (WillSaveTextDocumentNotification) { - WillSaveTextDocumentNotification.method = 'textDocument/willSave'; - WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method); -})(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {})); -/** - * A document will save request is sent from the client to the server before - * the document is actually saved. The request can return an array of TextEdits - * which will be applied to the text document before it is saved. Please note that - * clients might drop results if computing the text edits took too long or if a - * server constantly fails on this request. This is done to keep the save fast and - * reliable. - */ -var WillSaveTextDocumentWaitUntilRequest; -(function (WillSaveTextDocumentWaitUntilRequest) { - WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil'; - WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method); -})(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {})); -/** - * The watched files notification is sent from the client to the server when - * the client detects changes to file watched by the language client. - */ -var DidChangeWatchedFilesNotification; -(function (DidChangeWatchedFilesNotification) { - DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles'); -})(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {})); -/** - * The file event type - */ -var FileChangeType; -(function (FileChangeType) { - /** - * The file got created. - */ - FileChangeType.Created = 1; - /** - * The file got changed. - */ - FileChangeType.Changed = 2; - /** - * The file got deleted. - */ - FileChangeType.Deleted = 3; -})(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {})); -var WatchKind; -(function (WatchKind) { - /** - * Interested in create events. - */ - WatchKind.Create = 1; - /** - * Interested in change events - */ - WatchKind.Change = 2; - /** - * Interested in delete events - */ - WatchKind.Delete = 4; -})(WatchKind = exports.WatchKind || (exports.WatchKind = {})); -/** - * Diagnostics notification are sent from the server to the client to signal - * results of validation runs. - */ -var PublishDiagnosticsNotification; -(function (PublishDiagnosticsNotification) { - PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics'); -})(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {})); -/** - * How a completion was triggered - */ -var CompletionTriggerKind; -(function (CompletionTriggerKind) { - /** - * Completion was triggered by typing an identifier (24x7 code - * complete), manual invocation (e.g Ctrl+Space) or via API. - */ - CompletionTriggerKind.Invoked = 1; - /** - * Completion was triggered by a trigger character specified by - * the `triggerCharacters` properties of the `CompletionRegistrationOptions`. - */ - CompletionTriggerKind.TriggerCharacter = 2; - /** - * Completion was re-triggered as current completion list is incomplete - */ - CompletionTriggerKind.TriggerForIncompleteCompletions = 3; -})(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {})); -/** - * Request to request completion at a given text document position. The request's - * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response - * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList) - * or a Thenable that resolves to such. - * - * The request can delay the computation of the [`detail`](#CompletionItem.detail) - * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve` - * request. However, properties that are needed for the initial sorting and filtering, like `sortText`, - * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. - */ -var CompletionRequest; -(function (CompletionRequest) { - CompletionRequest.method = 'textDocument/completion'; - CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method); - /** @deprecated Use CompletionRequest.type */ - CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {})); -/** - * Request to resolve additional information for a given completion item.The request's - * parameter is of type [CompletionItem](#CompletionItem) the response - * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such. - */ -var CompletionResolveRequest; -(function (CompletionResolveRequest) { - CompletionResolveRequest.method = 'completionItem/resolve'; - CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method); -})(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {})); -/** - * Request to request hover information at a given text document position. The request's - * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of - * type [Hover](#Hover) or a Thenable that resolves to such. - */ -var HoverRequest; -(function (HoverRequest) { - HoverRequest.method = 'textDocument/hover'; - HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method); -})(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {})); -/** - * How a signature help was triggered. - * - * @since 3.15.0 - */ -var SignatureHelpTriggerKind; -(function (SignatureHelpTriggerKind) { - /** - * Signature help was invoked manually by the user or by a command. - */ - SignatureHelpTriggerKind.Invoked = 1; - /** - * Signature help was triggered by a trigger character. - */ - SignatureHelpTriggerKind.TriggerCharacter = 2; - /** - * Signature help was triggered by the cursor moving or by the document content changing. - */ - SignatureHelpTriggerKind.ContentChange = 3; -})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {})); -var SignatureHelpRequest; -(function (SignatureHelpRequest) { - SignatureHelpRequest.method = 'textDocument/signatureHelp'; - SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method); -})(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {})); -/** - * A request to resolve the definition location of a symbol at a given text - * document position. The request's parameter is of type [TextDocumentPosition] - * (#TextDocumentPosition) the response is of either type [Definition](#Definition) - * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves - * to such. - */ -var DefinitionRequest; -(function (DefinitionRequest) { - DefinitionRequest.method = 'textDocument/definition'; - DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method); - /** @deprecated Use DefinitionRequest.type */ - DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {})); -/** - * A request to resolve project-wide references for the symbol denoted - * by the given text document position. The request's parameter is of - * type [ReferenceParams](#ReferenceParams) the response is of type - * [Location[]](#Location) or a Thenable that resolves to such. - */ -var ReferencesRequest; -(function (ReferencesRequest) { - ReferencesRequest.method = 'textDocument/references'; - ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method); - /** @deprecated Use ReferencesRequest.type */ - ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {})); -/** - * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given - * text document position. The request's parameter is of type [TextDocumentPosition] - * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] - * (#DocumentHighlight) or a Thenable that resolves to such. - */ -var DocumentHighlightRequest; -(function (DocumentHighlightRequest) { - DocumentHighlightRequest.method = 'textDocument/documentHighlight'; - DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method); - /** @deprecated Use DocumentHighlightRequest.type */ - DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {})); -/** - * A request to list all symbols found in a given text document. The request's - * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the - * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable - * that resolves to such. - */ -var DocumentSymbolRequest; -(function (DocumentSymbolRequest) { - DocumentSymbolRequest.method = 'textDocument/documentSymbol'; - DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method); - /** @deprecated Use DocumentSymbolRequest.type */ - DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {})); -/** - * A request to provide commands for the given text document and range. - */ -var CodeActionRequest; -(function (CodeActionRequest) { - CodeActionRequest.method = 'textDocument/codeAction'; - CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method); - /** @deprecated Use CodeActionRequest.type */ - CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {})); -/** - * A request to list project-wide symbols matching the query string given - * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is - * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that - * resolves to such. - */ -var WorkspaceSymbolRequest; -(function (WorkspaceSymbolRequest) { - WorkspaceSymbolRequest.method = 'workspace/symbol'; - WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method); - /** @deprecated Use WorkspaceSymbolRequest.type */ - WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {})); -/** - * A request to provide code lens for the given text document. - */ -var CodeLensRequest; -(function (CodeLensRequest) { - CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens'); - /** @deprecated Use CodeLensRequest.type */ - CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {})); -/** - * A request to resolve a command for a given code lens. - */ -var CodeLensResolveRequest; -(function (CodeLensResolveRequest) { - CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve'); -})(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {})); -/** - * A request to provide document links - */ -var DocumentLinkRequest; -(function (DocumentLinkRequest) { - DocumentLinkRequest.method = 'textDocument/documentLink'; - DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method); - /** @deprecated Use DocumentLinkRequest.type */ - DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {})); -/** - * Request to resolve additional information for a given document link. The request's - * parameter is of type [DocumentLink](#DocumentLink) the response - * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such. - */ -var DocumentLinkResolveRequest; -(function (DocumentLinkResolveRequest) { - DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve'); -})(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {})); -/** - * A request to to format a whole document. - */ -var DocumentFormattingRequest; -(function (DocumentFormattingRequest) { - DocumentFormattingRequest.method = 'textDocument/formatting'; - DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method); -})(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {})); -/** - * A request to to format a range in a document. - */ -var DocumentRangeFormattingRequest; -(function (DocumentRangeFormattingRequest) { - DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting'; - DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method); -})(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {})); -/** - * A request to format a document on type. - */ -var DocumentOnTypeFormattingRequest; -(function (DocumentOnTypeFormattingRequest) { - DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting'; - DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method); -})(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {})); -/** - * A request to rename a symbol. - */ -var RenameRequest; -(function (RenameRequest) { - RenameRequest.method = 'textDocument/rename'; - RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method); -})(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {})); -/** - * A request to test and perform the setup necessary for a rename. - */ -var PrepareRenameRequest; -(function (PrepareRenameRequest) { - PrepareRenameRequest.method = 'textDocument/prepareRename'; - PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method); -})(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {})); -/** - * A request send from the client to the server to execute a command. The request might return - * a workspace edit which the client will apply to the workspace. - */ -var ExecuteCommandRequest; -(function (ExecuteCommandRequest) { - ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand'); -})(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {})); -/** - * A request sent from the server to the client to modified certain resources. - */ -var ApplyWorkspaceEditRequest; -(function (ApplyWorkspaceEditRequest) { - ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit'); -})(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {})); - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -function boolean(value) { - return value === true || value === false; -} -exports.boolean = boolean; -function string(value) { - return typeof value === 'string' || value instanceof String; -} -exports.string = string; -function number(value) { - return typeof value === 'number' || value instanceof Number; -} -exports.number = number; -function error(value) { - return value instanceof Error; -} -exports.error = error; -function func(value) { - return typeof value === 'function'; -} -exports.func = func; -function array(value) { - return Array.isArray(value); -} -exports.array = array; -function stringArray(value) { - return array(value) && value.every(elem => string(elem)); -} -exports.stringArray = stringArray; -function typedArray(value, check) { - return Array.isArray(value) && value.every(check); -} -exports.typedArray = typedArray; -function objectLiteral(value) { - // Strictly speaking class instances pass this check as well. Since the LSP - // doesn't use classes we ignore this for now. If we do we need to add something - // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` - return value !== null && typeof value === 'object'; -} -exports.objectLiteral = objectLiteral; - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 { - constructor(method) { - super(method); - } -} -exports.ProtocolRequestType0 = ProtocolRequestType0; -class ProtocolRequestType extends vscode_jsonrpc_1.RequestType { - constructor(method) { - super(method); - } -} -exports.ProtocolRequestType = ProtocolRequestType; -class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType { - constructor(method) { - super(method); - } -} -exports.ProtocolNotificationType = ProtocolNotificationType; -class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 { - constructor(method) { - super(method); - } -} -exports.ProtocolNotificationType0 = ProtocolNotificationType0; - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -// @ts-ignore: to avoid inlining LocatioLink as dynamic import -let __noDynamicImport; -/** - * A request to resolve the implementation locations of a symbol at a given text - * document position. The request's parameter is of type [TextDocumentPositioParams] - * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a - * Thenable that resolves to such. - */ -var ImplementationRequest; -(function (ImplementationRequest) { - ImplementationRequest.method = 'textDocument/implementation'; - ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method); - /** @deprecated Use ImplementationRequest.type */ - ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {})); - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -// @ts-ignore: to avoid inlining LocatioLink as dynamic import -let __noDynamicImport; -/** - * A request to resolve the type definition locations of a symbol at a given text - * document position. The request's parameter is of type [TextDocumentPositioParams] - * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a - * Thenable that resolves to such. - */ -var TypeDefinitionRequest; -(function (TypeDefinitionRequest) { - TypeDefinitionRequest.method = 'textDocument/typeDefinition'; - TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method); - /** @deprecated Use TypeDefinitionRequest.type */ - TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {})); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const messages_1 = __webpack_require__(226); -/** - * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. - */ -var WorkspaceFoldersRequest; -(function (WorkspaceFoldersRequest) { - WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders'); -})(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {})); -/** - * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace - * folder configuration changes. - */ -var DidChangeWorkspaceFoldersNotification; -(function (DidChangeWorkspaceFoldersNotification) { - DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders'); -})(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {})); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const messages_1 = __webpack_require__(226); -/** - * The 'workspace/configuration' request is sent from the server to the client to fetch a certain - * configuration setting. - * - * This pull model replaces the old push model were the client signaled configuration change via an - * event. If the server still needs to react to configuration changes (since the server caches the - * result of `workspace/configuration` requests) the server should register for an empty configuration - * change event and empty the cache if such an event is received. - */ -var ConfigurationRequest; -(function (ConfigurationRequest) { - ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration'); -})(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {})); - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -/** - * A request to list all color symbols found in a given text document. The request's - * parameter is of type [DocumentColorParams](#DocumentColorParams) the - * response is of type [ColorInformation[]](#ColorInformation) or a Thenable - * that resolves to such. - */ -var DocumentColorRequest; -(function (DocumentColorRequest) { - DocumentColorRequest.method = 'textDocument/documentColor'; - DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method); - /** @deprecated Use DocumentColorRequest.type */ - DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {})); -/** - * A request to list all presentation for a color. The request's - * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the - * response is of type [ColorInformation[]](#ColorInformation) or a Thenable - * that resolves to such. - */ -var ColorPresentationRequest; -(function (ColorPresentationRequest) { - ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation'); -})(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {})); - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -/** - * Enum of known range kinds - */ -var FoldingRangeKind; -(function (FoldingRangeKind) { - /** - * Folding range for a comment - */ - FoldingRangeKind["Comment"] = "comment"; - /** - * Folding range for a imports or includes - */ - FoldingRangeKind["Imports"] = "imports"; - /** - * Folding range for a region (e.g. `#region`) - */ - FoldingRangeKind["Region"] = "region"; -})(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {})); -/** - * A request to provide folding ranges in a document. The request's - * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the - * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable - * that resolves to such. - */ -var FoldingRangeRequest; -(function (FoldingRangeRequest) { - FoldingRangeRequest.method = 'textDocument/foldingRange'; - FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method); - /** @deprecated Use FoldingRangeRequest.type */ - FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {})); - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -// @ts-ignore: to avoid inlining LocatioLink as dynamic import -let __noDynamicImport; -/** - * A request to resolve the type definition locations of a symbol at a given text - * document position. The request's parameter is of type [TextDocumentPositioParams] - * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration) - * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves - * to such. - */ -var DeclarationRequest; -(function (DeclarationRequest) { - DeclarationRequest.method = 'textDocument/declaration'; - DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method); - /** @deprecated Use DeclarationRequest.type */ - DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {})); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -/** - * A request to provide selection ranges in a document. The request's - * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the - * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable - * that resolves to such. - */ -var SelectionRangeRequest; -(function (SelectionRangeRequest) { - SelectionRangeRequest.method = 'textDocument/selectionRange'; - SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method); - /** @deprecated Use SelectionRangeRequest.type */ - SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType(); -})(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {})); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_jsonrpc_1 = __webpack_require__(212); -const messages_1 = __webpack_require__(226); -var WorkDoneProgress; -(function (WorkDoneProgress) { - WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType(); -})(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {})); -/** - * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress - * reporting from the server. - */ -var WorkDoneProgressCreateRequest; -(function (WorkDoneProgressCreateRequest) { - WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create'); -})(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {})); -/** - * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress - * initiated on the server side. - */ -var WorkDoneProgressCancelNotification; -(function (WorkDoneProgressCancelNotification) { - WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel'); -})(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {})); - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) TypeFox and others. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const messages_1 = __webpack_require__(226); -/** - * A request to result a `CallHierarchyItem` in a document at a given position. - * Can be used as an input to a incoming or outgoing call hierarchy. - * - * @since 3.16.0 - Proposed state - */ -var CallHierarchyPrepareRequest; -(function (CallHierarchyPrepareRequest) { - CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy'; - CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method); -})(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {})); -/** - * A request to resolve the incoming calls for a given `CallHierarchyItem`. - * - * @since 3.16.0 - Proposed state - */ -var CallHierarchyIncomingCallsRequest; -(function (CallHierarchyIncomingCallsRequest) { - CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls'; - CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method); -})(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {})); -/** - * A request to resolve the outgoing calls for a given `CallHierarchyItem`. - * - * @since 3.16.0 - Proposed state - */ -var CallHierarchyOutgoingCallsRequest; -(function (CallHierarchyOutgoingCallsRequest) { - CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls'; - CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method); -})(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {})); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -Object.defineProperty(exports, "__esModule", { value: true }); -const messages_1 = __webpack_require__(226); -/** - * A set of predefined token types. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - Proposed state - */ -var SemanticTokenTypes; -(function (SemanticTokenTypes) { - SemanticTokenTypes["comment"] = "comment"; - SemanticTokenTypes["keyword"] = "keyword"; - SemanticTokenTypes["string"] = "string"; - SemanticTokenTypes["number"] = "number"; - SemanticTokenTypes["regexp"] = "regexp"; - SemanticTokenTypes["operator"] = "operator"; - SemanticTokenTypes["namespace"] = "namespace"; - SemanticTokenTypes["type"] = "type"; - SemanticTokenTypes["struct"] = "struct"; - SemanticTokenTypes["class"] = "class"; - SemanticTokenTypes["interface"] = "interface"; - SemanticTokenTypes["enum"] = "enum"; - SemanticTokenTypes["typeParameter"] = "typeParameter"; - SemanticTokenTypes["function"] = "function"; - SemanticTokenTypes["member"] = "member"; - SemanticTokenTypes["property"] = "property"; - SemanticTokenTypes["macro"] = "macro"; - SemanticTokenTypes["variable"] = "variable"; - SemanticTokenTypes["parameter"] = "parameter"; - SemanticTokenTypes["label"] = "label"; -})(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {})); -/** - * A set of predefined token modifiers. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - Proposed state - */ -var SemanticTokenModifiers; -(function (SemanticTokenModifiers) { - SemanticTokenModifiers["documentation"] = "documentation"; - SemanticTokenModifiers["declaration"] = "declaration"; - SemanticTokenModifiers["definition"] = "definition"; - SemanticTokenModifiers["reference"] = "reference"; - SemanticTokenModifiers["static"] = "static"; - SemanticTokenModifiers["abstract"] = "abstract"; - SemanticTokenModifiers["deprecated"] = "deprecated"; - SemanticTokenModifiers["async"] = "async"; - SemanticTokenModifiers["volatile"] = "volatile"; - SemanticTokenModifiers["readonly"] = "readonly"; -})(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {})); -/** - * @since 3.16.0 - Proposed state - */ -var SemanticTokens; -(function (SemanticTokens) { - function is(value) { - const candidate = value; - return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && - Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); - } - SemanticTokens.is = is; -})(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {})); -/** - * @since 3.16.0 - Proposed state - */ -var SemanticTokensRequest; -(function (SemanticTokensRequest) { - SemanticTokensRequest.method = 'textDocument/semanticTokens'; - SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method); -})(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {})); -/** - * @since 3.16.0 - Proposed state - */ -var SemanticTokensEditsRequest; -(function (SemanticTokensEditsRequest) { - SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits'; - SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method); -})(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {})); -/** - * @since 3.16.0 - Proposed state - */ -var SemanticTokensRangeRequest; -(function (SemanticTokensRangeRequest) { - SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range'; - SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method); -})(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {})); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.concurrent = exports.getKeymapModifier = exports.isRunning = exports.watchFile = exports.runCommand = exports.executable = exports.disposeAll = exports.getUri = exports.wait = exports.escapeSingleQuote = exports.CONFIG_FILE_NAME = exports.platform = void 0; -const tslib_1 = __webpack_require__(65); -const child_process_1 = __webpack_require__(239); -const debounce_1 = tslib_1.__importDefault(__webpack_require__(240)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const isuri_1 = tslib_1.__importDefault(__webpack_require__(241)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const which_1 = tslib_1.__importDefault(__webpack_require__(244)); -const platform = tslib_1.__importStar(__webpack_require__(248)); -exports.platform = platform; -const logger = __webpack_require__(64)('util-index'); -exports.CONFIG_FILE_NAME = 'coc-settings.json'; -function escapeSingleQuote(str) { - return str.replace(/'/g, "''"); -} -exports.escapeSingleQuote = escapeSingleQuote; -function wait(ms) { - return new Promise(resolve => { - setTimeout(() => { - resolve(); - }, ms); - }); -} -exports.wait = wait; -function getUri(fullpath, id, buftype, isCygwin) { - if (!fullpath) - return `untitled:${id}`; - if (platform.isWindows && !isCygwin) - fullpath = path_1.default.win32.normalize(fullpath); - if (path_1.default.isAbsolute(fullpath)) - return vscode_uri_1.URI.file(fullpath).toString(); - if (isuri_1.default.isValid(fullpath)) - return vscode_uri_1.URI.parse(fullpath).toString(); - if (buftype != '') - return `${buftype}:${id}`; - return `unknown:${id}`; -} -exports.getUri = getUri; -function disposeAll(disposables) { - while (disposables.length) { - const item = disposables.pop(); - if (item) { - item.dispose(); - } - } -} -exports.disposeAll = disposeAll; -function executable(command) { - try { - which_1.default.sync(command); - } - catch (e) { - return false; - } - return true; -} -exports.executable = executable; -function runCommand(cmd, opts = {}, timeout) { - if (!platform.isWindows) { - opts.shell = opts.shell || process.env.SHELL; - } - opts.maxBuffer = 500 * 1024; - return new Promise((resolve, reject) => { - let timer; - if (timeout) { - timer = setTimeout(() => { - reject(new Error(`timeout after ${timeout}s`)); - }, timeout * 1000); - } - child_process_1.exec(cmd, opts, (err, stdout, stderr) => { - if (timer) - clearTimeout(timer); - if (err) { - reject(new Error(`exited with ${err.code}\n${err}\n${stderr}`)); - return; - } - resolve(stdout); - }); - }); -} -exports.runCommand = runCommand; -function watchFile(filepath, onChange) { - let callback = debounce_1.default(onChange, 100); - try { - let watcher = fs_1.default.watch(filepath, { - persistent: true, - recursive: false, - encoding: 'utf8' - }, () => { - callback(); - }); - return vscode_languageserver_protocol_1.Disposable.create(() => { - callback.clear(); - watcher.close(); - }); - } - catch (e) { - return vscode_languageserver_protocol_1.Disposable.create(() => { - callback.clear(); - }); - } -} -exports.watchFile = watchFile; -function isRunning(pid) { - try { - let res = process.kill(pid, 0); - return res == true; - } - catch (e) { - return e.code === 'EPERM'; - } -} -exports.isRunning = isRunning; -function getKeymapModifier(mode) { - if (mode == 'n' || mode == 'o' || mode == 'x' || mode == 'v') - return ''; - if (mode == 'i') - return ''; - if (mode == 's') - return ''; - return ''; -} -exports.getKeymapModifier = getKeymapModifier; -function concurrent(arr, fn, limit = 3) { - if (arr.length == 0) - return Promise.resolve(); - let finished = 0; - let total = arr.length; - let remain = arr.slice(); - return new Promise(resolve => { - let run = (val) => { - let cb = () => { - finished = finished + 1; - if (finished == total) { - resolve(); - } - else if (remain.length) { - let next = remain.shift(); - run(next); - } - }; - fn(val).then(cb, cb); - }; - for (let i = 0; i < Math.min(limit, remain.length); i++) { - let val = remain.shift(); - run(val); - } - }); -} -exports.concurrent = concurrent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 239 */ -/***/ (function(module, exports) { - -module.exports = require("child_process"); - -/***/ }), -/* 240 */ -/***/ (function(module, exports) { - -/** - * Returns a function, that, as long as it continues to be invoked, will not - * be triggered. The function will be called after it stops being called for - * N milliseconds. If `immediate` is passed, trigger the function on the - * leading edge, instead of the trailing. The function also has a property 'clear' - * that is a function which will clear the timer to prevent previously scheduled executions. - * - * @source underscore.js - * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ - * @param {Function} function to wrap - * @param {Number} timeout in ms (`100`) - * @param {Boolean} whether to execute at the beginning (`false`) - * @api public - */ -function debounce(func, wait, immediate){ - var timeout, args, context, timestamp, result; - if (null == wait) wait = 100; - - function later() { - var last = Date.now() - timestamp; - - if (last < wait && last >= 0) { - timeout = setTimeout(later, wait - last); - } else { - timeout = null; - if (!immediate) { - result = func.apply(context, args); - context = args = null; - } - } - }; - - var debounced = function(){ - context = this; - args = arguments; - timestamp = Date.now(); - var callNow = immediate && !timeout; - if (!timeout) timeout = setTimeout(later, wait); - if (callNow) { - result = func.apply(context, args); - context = args = null; - } - - return result; - }; - - debounced.clear = function() { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - }; - - debounced.flush = function() { - if (timeout) { - result = func.apply(context, args); - context = args = null; - - clearTimeout(timeout); - timeout = null; - } - }; - - return debounced; -}; - -// Adds compatibility for ES modules -debounce.debounce = debounce; - -module.exports = debounce; - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var rfc3986 = __webpack_require__(242); - -// See: https://github.com/hapijs/hoek/blob/f62961d3d07aca68ab11480893e6e80a421914b4/lib/index.js#L783-L787 -function escapeRegex(string) { - // Escape ^$.*+-?=!:|\/()[]{}, - return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); -} - -var internals = { - Uri: { - createUriRegex: function (options) { - options = options || {}; - - if (typeof options !== 'object' || Array.isArray(options)) { - throw new Error('options must be an object'); - } - - var customScheme = ''; - - // If we were passed a scheme, use it instead of the generic one - if (options.scheme) { - if (!Array.isArray(options.scheme)) { - options.scheme = [options.scheme]; - } - - if (options.scheme.length <= 0) { - throw new Error('scheme must have at least 1 scheme specified'); - } - - for (var i = 0; i < options.scheme.length; ++i) { - var currentScheme = options.scheme[i]; - - if (!(currentScheme instanceof RegExp || typeof currentScheme === 'string')) { - throw new Error('scheme must only contain Regular Expressions or Strings'); - } - - // Add OR separators if a value already exists - customScheme = customScheme + (customScheme ? '|' : ''); - - // If someone wants to match HTTP or HTTPS for example then we need to support both RegExp and String so we don't escape their pattern unknowingly. - if (currentScheme instanceof RegExp) { - customScheme = customScheme + currentScheme.source; - } else { - if (!/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(currentScheme)) { - throw new Error('scheme at position ' + i + ' must be a valid scheme'); - } - customScheme = customScheme + escapeRegex(currentScheme); - } - } - - } - - // Have to put this in a non-capturing group to handle the OR statements - var scheme = '(?:' + (customScheme || rfc3986.scheme) + ')'; - - /** - * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - * - * OR - * - * relative-ref = relative-part [ "?" query ] [ "#" fragment ] - */ - return new RegExp('^(?:' + scheme + ':' + rfc3986.hierPart + ')(?:\\?' + rfc3986.query + ')?(?:#' + rfc3986.fragment + ')?$'); - }, - uriRegex: new RegExp(rfc3986.uri) - } -}; - -internals.Uri.isValid = function (val) { - return internals.Uri.uriRegex.test(val); -}; - -module.exports = { - createUriRegex: internals.Uri.createUriRegex, - - uriRegex: internals.Uri.uriRegex, - isValid: internals.Uri.isValid -}; - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// Load modules - -// Delcare internals - -var internals = { - rfc3986: {} -}; - -internals.generate = function () { - - /** - * elements separated by forward slash ("/") are alternatives. - */ - var or = '|'; - - /** - * DIGIT = %x30-39 ; 0-9 - */ - var digit = '0-9'; - var digitOnly = '[' + digit + ']'; - - /** - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - */ - var alpha = 'a-zA-Z'; - var alphaOnly = '[' + alpha + ']'; - - /** - * cidr = DIGIT ; 0-9 - * / %x31-32 DIGIT ; 10-29 - * / "3" %x30-32 ; 30-32 - */ - internals.rfc3986.cidr = digitOnly + or + '[1-2]' + digitOnly + or + '3' + '[0-2]'; - - /** - * HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" - */ - var hexDigit = digit + 'A-Fa-f'; - var hexDigitOnly = '[' + hexDigit + ']'; - - /** - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - */ - var unreserved = alpha + digit + '-\\._~'; - - /** - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - */ - var subDelims = '!\\$&\'\\(\\)\\*\\+,;='; - - /** - * pct-encoded = "%" HEXDIG HEXDIG - */ - var pctEncoded = '%' + hexDigit; - - /** - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ - var pchar = unreserved + pctEncoded + subDelims + ':@'; - var pcharOnly = '[' + pchar + ']'; - - /** - * Rule to support zero-padded addresses. - */ - var zeroPad = '0?'; - - /** - * dec-octet = DIGIT ; 0-9 - * / %x31-39 DIGIT ; 10-99 - * / "1" 2DIGIT ; 100-199 - * / "2" %x30-34 DIGIT ; 200-249 - * / "25" %x30-35 ; 250-255 - */ - var decOctect = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + digitOnly + digitOnly + or + '2' + '[0-4]' + digitOnly + or + '25' + '[0-5])'; - - /** - * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - */ - internals.rfc3986.IPv4address = '(?:' + decOctect + '\\.){3}' + decOctect; - - /** - * h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - * ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address - * IPv6address = 6( h16 ":" ) ls32 - * / "::" 5( h16 ":" ) ls32 - * / [ h16 ] "::" 4( h16 ":" ) ls32 - * / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - * / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - * / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - * / [ *4( h16 ":" ) h16 ] "::" ls32 - * / [ *5( h16 ":" ) h16 ] "::" h16 - * / [ *6( h16 ":" ) h16 ] "::" - */ - var h16 = hexDigitOnly + '{1,4}'; - var ls32 = '(?:' + h16 + ':' + h16 + '|' + internals.rfc3986.IPv4address + ')'; - var IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; - var IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; - var IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; - var IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; - var IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; - var IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; - var IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; - var IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; - var IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; - internals.rfc3986.IPv6address = '(?:' + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ')'; - - /** - * IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - */ - internals.rfc3986.IPvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; - - /** - * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - */ - internals.rfc3986.scheme = alphaOnly + '[' + alpha + digit + '+-\\.]*'; - - /** - * userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) - */ - var userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; - - /** - * IP-literal = "[" ( IPv6address / IPvFuture ) "]" - */ - internals.rfc3986.IPLiteral = '\\[(?:' + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ')\\]'; - - /** - * reg-name = *( unreserved / pct-encoded / sub-delims ) - */ - var regName = '[' + unreserved + pctEncoded + subDelims + ']{0,255}'; - - /** - * host = IP-literal / IPv4address / reg-name - */ - var host = '(?:' + internals.rfc3986.IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ')'; - - /** - * port = *DIGIT - */ - var port = digitOnly + '*'; - - /** - * authority = [ userinfo "@" ] host [ ":" port ] - */ - var authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; - - /** - * segment = *pchar - * segment-nz = 1*pchar - * path = path-abempty ; begins with "/" or is empty - * / path-absolute ; begins with "/" but not "//" - * / path-noscheme ; begins with a non-colon segment - * / path-rootless ; begins with a segment - * / path-empty ; zero characters - * path-abempty = *( "/" segment ) - * path-absolute = "/" [ segment-nz *( "/" segment ) ] - * path-rootless = segment-nz *( "/" segment ) - */ - var segment = pcharOnly + '*'; - var segmentNz = pcharOnly + '+'; - var pathAbEmpty = '(?:\\/' + segment + ')*'; - var pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; - var pathRootless = segmentNz + pathAbEmpty; - - /** - * hier-part = "//" authority path - */ - internals.rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathRootless + ')'; - - /** - * query = *( pchar / "/" / "?" ) - */ - internals.rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. - - /** - * fragment = *( pchar / "/" / "?" ) - */ - internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*'; - - /** - * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - * - * OR - * - * relative-ref = relative-part [ "?" query ] [ "#" fragment ] - */ - internals.rfc3986.uri = '^(?:' + internals.rfc3986.scheme + ':' + internals.rfc3986.hierPart + ')(?:\\?' + internals.rfc3986.query + ')?' + '(?:#' + internals.rfc3986.fragment + ')?$'; -}; - -internals.generate(); - -module.exports = internals.rfc3986; - -/***/ }), -/* 243 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uriToFsPath", function() { return uriToFsPath; }); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var _a; -var isWindows; -if (typeof process === 'object') { - isWindows = process.platform === 'win32'; -} -else if (typeof navigator === 'object') { - var userAgent = navigator.userAgent; - isWindows = userAgent.indexOf('Windows') >= 0; -} -function isHighSurrogate(charCode) { - return (0xD800 <= charCode && charCode <= 0xDBFF); -} -function isLowSurrogate(charCode) { - return (0xDC00 <= charCode && charCode <= 0xDFFF); -} -function isLowerAsciiHex(code) { - return code >= 97 /* a */ && code <= 102 /* f */; -} -function isLowerAsciiLetter(code) { - return code >= 97 /* a */ && code <= 122 /* z */; -} -function isUpperAsciiLetter(code) { - return code >= 65 /* A */ && code <= 90 /* Z */; -} -function isAsciiLetter(code) { - return isLowerAsciiLetter(code) || isUpperAsciiLetter(code); -} -//#endregion -var _schemePattern = /^\w[\w\d+.-]*$/; -var _singleSlashStart = /^\//; -var _doubleSlashStart = /^\/\//; -function _validateUri(ret, _strict) { - // scheme, must be set - if (!ret.scheme && _strict) { - throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}"); - } - // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 - // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - if (ret.scheme && !_schemePattern.test(ret.scheme)) { - throw new Error('[UriError]: Scheme contains illegal characters.'); - } - // path, http://tools.ietf.org/html/rfc3986#section-3.3 - // If a URI contains an authority component, then the path component - // must either be empty or begin with a slash ("/") character. If a URI - // does not contain an authority component, then the path cannot begin - // with two slash characters ("//"). - if (ret.path) { - if (ret.authority) { - if (!_singleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); - } - } - else { - if (_doubleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); - } - } - } -} -// for a while we allowed uris *without* schemes and this is the migration -// for them, e.g. an uri without scheme and without strict-mode warns and falls -// back to the file-scheme. that should cause the least carnage and still be a -// clear warning -function _schemeFix(scheme, _strict) { - if (!scheme && !_strict) { - return 'file'; - } - return scheme; -} -// implements a bit of https://tools.ietf.org/html/rfc3986#section-5 -function _referenceResolution(scheme, path) { - // the slash-character is our 'default base' as we don't - // support constructing URIs relative to other URIs. This - // also means that we alter and potentially break paths. - // see https://tools.ietf.org/html/rfc3986#section-5.1.4 - switch (scheme) { - case 'https': - case 'http': - case 'file': - if (!path) { - path = _slash; - } - else if (path[0] !== _slash) { - path = _slash + path; - } - break; - } - return path; -} -var _empty = ''; -var _slash = '/'; -var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; -/** - * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. - * This class is a simple parser which creates the basic component parts - * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation - * and encoding. - * - * ```txt - * foo://example.com:8042/over/there?name=ferret#nose - * \_/ \______________/\_________/ \_________/ \__/ - * | | | | | - * scheme authority path query fragment - * | _____________________|__ - * / \ / \ - * urn:example:animal:ferret:nose - * ``` - */ -var URI = /** @class */ (function () { - /** - * @internal - */ - function URI(schemeOrData, authority, path, query, fragment, _strict) { - if (_strict === void 0) { _strict = false; } - if (typeof schemeOrData === 'object') { - this.scheme = schemeOrData.scheme || _empty; - this.authority = schemeOrData.authority || _empty; - this.path = schemeOrData.path || _empty; - this.query = schemeOrData.query || _empty; - this.fragment = schemeOrData.fragment || _empty; - // no validation because it's this URI - // that creates uri components. - // _validateUri(this); - } - else { - this.scheme = _schemeFix(schemeOrData, _strict); - this.authority = authority || _empty; - this.path = _referenceResolution(this.scheme, path || _empty); - this.query = query || _empty; - this.fragment = fragment || _empty; - _validateUri(this, _strict); - } - } - URI.isUri = function (thing) { - if (thing instanceof URI) { - return true; - } - if (!thing) { - return false; - } - return typeof thing.authority === 'string' - && typeof thing.fragment === 'string' - && typeof thing.path === 'string' - && typeof thing.query === 'string' - && typeof thing.scheme === 'string' - && typeof thing.fsPath === 'function' - && typeof thing.with === 'function' - && typeof thing.toString === 'function'; - }; - Object.defineProperty(URI.prototype, "fsPath", { - // ---- filesystem path ----------------------- - /** - * Returns a string representing the corresponding file system path of this URI. - * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the - * platform specific path separator. - * - * * Will *not* validate the path for invalid characters and semantics. - * * Will *not* look at the scheme of this URI. - * * The result shall *not* be used for display purposes but for accessing a file on disk. - * - * - * The *difference* to `URI#path` is the use of the platform specific separator and the handling - * of UNC paths. See the below sample of a file-uri with an authority (UNC path). - * - * ```ts - const u = URI.parse('file://server/c$/folder/file.txt') - u.authority === 'server' - u.path === '/shares/c$/file.txt' - u.fsPath === '\\server\c$\folder\file.txt' - ``` - * - * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, - * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working - * with URIs that represent files on disk (`file` scheme). - */ - get: function () { - // if (this.scheme !== 'file') { - // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); - // } - return uriToFsPath(this, false); - }, - enumerable: true, - configurable: true - }); - // ---- modify to new ------------------------- - URI.prototype.with = function (change) { - if (!change) { - return this; - } - var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment; - if (scheme === undefined) { - scheme = this.scheme; - } - else if (scheme === null) { - scheme = _empty; - } - if (authority === undefined) { - authority = this.authority; - } - else if (authority === null) { - authority = _empty; - } - if (path === undefined) { - path = this.path; - } - else if (path === null) { - path = _empty; - } - if (query === undefined) { - query = this.query; - } - else if (query === null) { - query = _empty; - } - if (fragment === undefined) { - fragment = this.fragment; - } - else if (fragment === null) { - fragment = _empty; - } - if (scheme === this.scheme - && authority === this.authority - && path === this.path - && query === this.query - && fragment === this.fragment) { - return this; - } - return new _URI(scheme, authority, path, query, fragment); - }; - // ---- parse & validate ------------------------ - /** - * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, - * `file:///usr/home`, or `scheme:with/path`. - * - * @param value A string which represents an URI (see `URI#toString`). - */ - URI.parse = function (value, _strict) { - if (_strict === void 0) { _strict = false; } - var match = _regexp.exec(value); - if (!match) { - return new _URI(_empty, _empty, _empty, _empty, _empty); - } - return new _URI(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict); - }; - /** - * Creates a new URI from a file system path, e.g. `c:\my\files`, - * `/usr/home`, or `\\server\share\some\path`. - * - * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument - * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** - * `URI.parse('file://' + path)` because the path might contain characters that are - * interpreted (# and ?). See the following sample: - * ```ts - const good = URI.file('/coding/c#/project1'); - good.scheme === 'file'; - good.path === '/coding/c#/project1'; - good.fragment === ''; - const bad = URI.parse('file://' + '/coding/c#/project1'); - bad.scheme === 'file'; - bad.path === '/coding/c'; // path is now broken - bad.fragment === '/project1'; - ``` - * - * @param path A file system path (see `URI#fsPath`) - */ - URI.file = function (path) { - var authority = _empty; - // normalize to fwd-slashes on windows, - // on other systems bwd-slashes are valid - // filename character, eg /f\oo/ba\r.txt - if (isWindows) { - path = path.replace(/\\/g, _slash); - } - // check for authority as used in UNC shares - // or use the path as given - if (path[0] === _slash && path[1] === _slash) { - var idx = path.indexOf(_slash, 2); - if (idx === -1) { - authority = path.substring(2); - path = _slash; - } - else { - authority = path.substring(2, idx); - path = path.substring(idx) || _slash; - } - } - return new _URI('file', authority, path, _empty, _empty); - }; - URI.from = function (components) { - return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment); - }; - // /** - // * Join a URI path with path fragments and normalizes the resulting path. - // * - // * @param uri The input URI. - // * @param pathFragment The path fragment to add to the URI path. - // * @returns The resulting URI. - // */ - // static joinPath(uri: URI, ...pathFragment: string[]): URI { - // if (!uri.path) { - // throw new Error(`[UriError]: cannot call joinPaths on URI without path`); - // } - // let newPath: string; - // if (isWindows && uri.scheme === 'file') { - // newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path; - // } else { - // newPath = paths.posix.join(uri.path, ...pathFragment); - // } - // return uri.with({ path: newPath }); - // } - // ---- printing/externalize --------------------------- - /** - * Creates a string representation for this URI. It's guaranteed that calling - * `URI.parse` with the result of this function creates an URI which is equal - * to this URI. - * - * * The result shall *not* be used for display purposes but for externalization or transport. - * * The result will be encoded using the percentage encoding and encoding happens mostly - * ignore the scheme-specific encoding rules. - * - * @param skipEncoding Do not encode the result, default is `false` - */ - URI.prototype.toString = function (skipEncoding) { - if (skipEncoding === void 0) { skipEncoding = false; } - return _asFormatted(this, skipEncoding); - }; - URI.prototype.toJSON = function () { - return this; - }; - URI.revive = function (data) { - if (!data) { - return data; - } - else if (data instanceof URI) { - return data; - } - else { - var result = new _URI(data); - result._formatted = data.external; - result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null; - return result; - } - }; - return URI; -}()); - -var _pathSepMarker = isWindows ? 1 : undefined; -// eslint-disable-next-line @typescript-eslint/class-name-casing -var _URI = /** @class */ (function (_super) { - __extends(_URI, _super); - function _URI() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._formatted = null; - _this._fsPath = null; - return _this; - } - Object.defineProperty(_URI.prototype, "fsPath", { - get: function () { - if (!this._fsPath) { - this._fsPath = uriToFsPath(this, false); - } - return this._fsPath; - }, - enumerable: true, - configurable: true - }); - _URI.prototype.toString = function (skipEncoding) { - if (skipEncoding === void 0) { skipEncoding = false; } - if (!skipEncoding) { - if (!this._formatted) { - this._formatted = _asFormatted(this, false); - } - return this._formatted; - } - else { - // we don't cache that - return _asFormatted(this, true); - } - }; - _URI.prototype.toJSON = function () { - var res = { - $mid: 1 - }; - // cached state - if (this._fsPath) { - res.fsPath = this._fsPath; - res._sep = _pathSepMarker; - } - if (this._formatted) { - res.external = this._formatted; - } - // uri components - if (this.path) { - res.path = this.path; - } - if (this.scheme) { - res.scheme = this.scheme; - } - if (this.authority) { - res.authority = this.authority; - } - if (this.query) { - res.query = this.query; - } - if (this.fragment) { - res.fragment = this.fragment; - } - return res; - }; - return _URI; -}(URI)); -// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 -var encodeTable = (_a = {}, - _a[58 /* Colon */] = '%3A', - _a[47 /* Slash */] = '%2F', - _a[63 /* QuestionMark */] = '%3F', - _a[35 /* Hash */] = '%23', - _a[91 /* OpenSquareBracket */] = '%5B', - _a[93 /* CloseSquareBracket */] = '%5D', - _a[64 /* AtSign */] = '%40', - _a[33 /* ExclamationMark */] = '%21', - _a[36 /* DollarSign */] = '%24', - _a[38 /* Ampersand */] = '%26', - _a[39 /* SingleQuote */] = '%27', - _a[40 /* OpenParen */] = '%28', - _a[41 /* CloseParen */] = '%29', - _a[42 /* Asterisk */] = '%2A', - _a[43 /* Plus */] = '%2B', - _a[44 /* Comma */] = '%2C', - _a[59 /* Semicolon */] = '%3B', - _a[61 /* Equals */] = '%3D', - _a[32 /* Space */] = '%20', - _a); -function encodeURIComponentFast(uriComponent, allowSlash) { - var res = undefined; - var nativeEncodePos = -1; - for (var pos = 0; pos < uriComponent.length; pos++) { - var code = uriComponent.charCodeAt(pos); - // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 - if ((code >= 97 /* a */ && code <= 122 /* z */) - || (code >= 65 /* A */ && code <= 90 /* Z */) - || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) - || code === 45 /* Dash */ - || code === 46 /* Period */ - || code === 95 /* Underline */ - || code === 126 /* Tilde */ - || (allowSlash && code === 47 /* Slash */)) { - // check if we are delaying native encode - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - // check if we write into a new string (by default we try to return the param) - if (res !== undefined) { - res += uriComponent.charAt(pos); - } - } - else { - // encoding needed, we need to allocate a new string - if (res === undefined) { - res = uriComponent.substr(0, pos); - } - // check with default table first - var escaped = encodeTable[code]; - if (escaped !== undefined) { - // check if we are delaying native encode - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - // append escaped variant to result - res += escaped; - } - else if (nativeEncodePos === -1) { - // use native encode only when needed - nativeEncodePos = pos; - } - } - } - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); - } - return res !== undefined ? res : uriComponent; -} -function encodeURIComponentMinimal(path) { - var res = undefined; - for (var pos = 0; pos < path.length; pos++) { - var code = path.charCodeAt(pos); - if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) { - if (res === undefined) { - res = path.substr(0, pos); - } - res += encodeTable[code]; - } - else { - if (res !== undefined) { - res += path[pos]; - } - } - } - return res !== undefined ? res : path; -} -/** - * Compute `fsPath` for the given uri - */ -function uriToFsPath(uri, keepDriveLetterCasing) { - var value; - if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') { - // unc path: file://shares/c$/far/boo - value = "//" + uri.authority + uri.path; - } - else if (uri.path.charCodeAt(0) === 47 /* Slash */ - && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */) - && uri.path.charCodeAt(2) === 58 /* Colon */) { - if (!keepDriveLetterCasing) { - // windows drive letter: file:///c:/far/boo - value = uri.path[1].toLowerCase() + uri.path.substr(2); - } - else { - value = uri.path.substr(1); - } - } - else { - // other path - value = uri.path; - } - if (isWindows) { - value = value.replace(/\//g, '\\'); - } - return value; -} -/** - * Create the external version of a uri - */ -function _asFormatted(uri, skipEncoding) { - var encoder = !skipEncoding - ? encodeURIComponentFast - : encodeURIComponentMinimal; - var res = ''; - var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment; - if (scheme) { - res += scheme; - res += ':'; - } - if (authority || scheme === 'file') { - res += _slash; - res += _slash; - } - if (authority) { - var idx = authority.indexOf('@'); - if (idx !== -1) { - // @ - var userinfo = authority.substr(0, idx); - authority = authority.substr(idx + 1); - idx = userinfo.indexOf(':'); - if (idx === -1) { - res += encoder(userinfo, false); - } - else { - // :@ - res += encoder(userinfo.substr(0, idx), false); - res += ':'; - res += encoder(userinfo.substr(idx + 1), false); - } - res += '@'; - } - authority = authority.toLowerCase(); - idx = authority.indexOf(':'); - if (idx === -1) { - res += encoder(authority, false); - } - else { - // : - res += encoder(authority.substr(0, idx), false); - res += authority.substr(idx); - } - } - if (path) { - // lower-case windows drive letters in /C:/fff or C:/fff - if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) { - var code = path.charCodeAt(1); - if (code >= 65 /* A */ && code <= 90 /* Z */) { - path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3 - } - } - else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) { - var code = path.charCodeAt(0); - if (code >= 65 /* A */ && code <= 90 /* Z */) { - path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3 - } - } - // encode the rest of the path - res += encoder(path, true); - } - if (query) { - res += '?'; - res += encoder(query, false); - } - if (fragment) { - res += '#'; - res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment; - } - return res; -} -// --- decode -function decodeURIComponentGraceful(str) { - try { - return decodeURIComponent(str); - } - catch (_a) { - if (str.length > 3) { - return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); - } - else { - return str; - } - } -} -var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; -function percentDecode(str) { - if (!str.match(_rEncodedAsHex)) { - return str; - } - return str.replace(_rEncodedAsHex, function (match) { return decodeURIComponentGraceful(match); }); -} - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' - -const path = __webpack_require__(82) -const COLON = isWindows ? ';' : ':' -const isexe = __webpack_require__(245) - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) - -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ) - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : '' - const pathExt = isWindows ? pathExtExe.split(colon) : [''] - - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') - } - - return { - pathEnv, - pathExt, - pathExtExe, - } -} - -const which = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt - opt = {} - } - if (!opt) - opt = {} - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) - - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw - - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - - resolve(subStep(p, i, 0)) - }) - - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }) - }) - - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -} - -const whichSync = (cmd, opt) => { - opt = opt || {} - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw - - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j] - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur - } - } catch (ex) {} - } - } - - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null - - throw getNotFoundError(cmd) -} - -module.exports = which -which.sync = whichSync - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - -var fs = __webpack_require__(66) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(246) -} else { - core = __webpack_require__(247) -} - -module.exports = isexe -isexe.sync = sync - -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } - - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } - - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } - - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } - } - cb(er, is) - }) -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = isexe -isexe.sync = sync - -var fs = __webpack_require__(66) - -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT - - if (!pathext) { - return true - } - - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} - -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} - -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} - -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = isexe -isexe.sync = sync - -var fs = __webpack_require__(66) - -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} - -function sync (path, options) { - return checkStat(fs.statSync(path), options) -} - -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} - -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() - - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g - - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 - - return ret -} - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OS = exports.globals = exports.platform = exports.isWeb = exports.isNative = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.Platform = exports.language = void 0; -let _isWindows = false; -let _isMacintosh = false; -let _isLinux = false; -let _isNative = false; -let _isWeb = false; -exports.language = 'en'; -// OS detection -if (typeof process === 'object' && - typeof process.nextTick === 'function' && - typeof process.platform === 'string') { - _isWindows = process.platform === 'win32'; - _isMacintosh = process.platform === 'darwin'; - _isLinux = process.platform === 'linux'; - _isNative = true; -} -var Platform; -(function (Platform) { - Platform[Platform["Web"] = 0] = "Web"; - Platform[Platform["Mac"] = 1] = "Mac"; - Platform[Platform["Linux"] = 2] = "Linux"; - Platform[Platform["Windows"] = 3] = "Windows"; -})(Platform = exports.Platform || (exports.Platform = {})); -let _platform = Platform.Web; -if (_isNative) { - if (_isMacintosh) { - _platform = Platform.Mac; - } - else if (_isWindows) { - _platform = Platform.Windows; - } - else if (_isLinux) { - _platform = Platform.Linux; - } -} -exports.isWindows = _isWindows; -exports.isMacintosh = _isMacintosh; -exports.isLinux = _isLinux; -exports.isNative = _isNative; -exports.isWeb = _isWeb; -exports.platform = _platform; -const _globals = typeof self === 'object' - ? self - : typeof global === 'object' - ? global - : {}; -exports.globals = _globals; -exports.OS = _isMacintosh - ? 2 /* Macintosh */ - : _isWindows - ? 1 /* Windows */ - : 3 /* Linux */; -//# sourceMappingURL=platform.js.map - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.equals = exports.mixin = exports.deepFreeze = exports.deepClone = void 0; -const tslib_1 = __webpack_require__(65); -const Is = tslib_1.__importStar(__webpack_require__(250)); -function deepClone(obj) { - if (!obj || typeof obj !== 'object') { - return obj; - } - if (obj instanceof RegExp) { - // See https://github.com/Microsoft/TypeScript/issues/10990 - return obj; - } - const result = Array.isArray(obj) ? [] : {}; - Object.keys(obj).forEach(key => { - if (obj[key] && typeof obj[key] === 'object') { - result[key] = deepClone(obj[key]); - } - else { - result[key] = obj[key]; - } - }); - return result; -} -exports.deepClone = deepClone; -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function deepFreeze(obj) { - if (!obj || typeof obj !== 'object') { - return obj; - } - const stack = [obj]; - while (stack.length > 0) { - let obj = stack.shift(); - Object.freeze(obj); - for (const key in obj) { - if (_hasOwnProperty.call(obj, key)) { - let prop = obj[key]; - if (typeof prop === 'object' && !Object.isFrozen(prop)) { - stack.push(prop); - } - } - } - } - return obj; -} -exports.deepFreeze = deepFreeze; -/** - * Copies all properties of source into destination. The optional parameter "overwrite" allows to control - * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite). - */ -function mixin(destination, source, overwrite = true) { - if (!Is.objectLiteral(destination)) { - return source; - } - if (Is.objectLiteral(source)) { - Object.keys(source).forEach(key => { - if (key in destination) { - if (overwrite) { - if (Is.objectLiteral(destination[key]) && Is.objectLiteral(source[key])) { - mixin(destination[key], source[key], overwrite); - } - else { - destination[key] = source[key]; - } - } - } - else { - destination[key] = source[key]; - } - }); - } - return destination; -} -exports.mixin = mixin; -function equals(one, other) { - if (one === other) { - return true; - } - if (one === null || - one === undefined || - other === null || - other === undefined) { - return false; - } - if (typeof one !== typeof other) { - return false; - } - if (typeof one !== 'object') { - return false; - } - if (Array.isArray(one) !== Array.isArray(other)) { - return false; - } - let i; - let key; - if (Array.isArray(one)) { - if (one.length !== other.length) { - return false; - } - for (i = 0; i < one.length; i++) { - if (!equals(one[i], other[i])) { - return false; - } - } - } - else { - const oneKeys = []; - for (key in one) { - oneKeys.push(key); - } - oneKeys.sort(); - const otherKeys = []; - for (key in other) { - otherKeys.push(key); - } - otherKeys.sort(); - if (!equals(oneKeys, otherKeys)) { - return false; - } - for (i = 0; i < oneKeys.length; i++) { - if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { - return false; - } - } - } - return true; -} -exports.equals = equals; -//# sourceMappingURL=object.js.map - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.typedArray = exports.emptyObject = exports.objectLiteral = exports.func = exports.array = exports.number = exports.string = exports.boolean = void 0; -/* eslint-disable id-blacklist */ -const hasOwnProperty = Object.prototype.hasOwnProperty; -function boolean(value) { - return typeof value === 'boolean'; -} -exports.boolean = boolean; -function string(value) { - return typeof value === 'string'; -} -exports.string = string; -function number(value) { - return typeof value === 'number'; -} -exports.number = number; -function array(array) { - return Array.isArray(array); -} -exports.array = array; -function func(value) { - return typeof value == 'function'; -} -exports.func = func; -function objectLiteral(obj) { - return (obj != null && - typeof obj === 'object' && - !Array.isArray(obj) && - !(obj instanceof RegExp) && - !(obj instanceof Date)); -} -exports.objectLiteral = objectLiteral; -function emptyObject(obj) { - if (!objectLiteral(obj)) { - return false; - } - for (let key in obj) { - if (hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; -} -exports.emptyObject = emptyObject; -function typedArray(value, check) { - return Array.isArray(value) && value.every(check); -} -exports.typedArray = typedArray; -//# sourceMappingURL=is.js.map - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const events_1 = __webpack_require__(198); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const commands_1 = tslib_1.__importDefault(__webpack_require__(252)); -const completion_1 = tslib_1.__importDefault(__webpack_require__(340)); -const cursors_1 = tslib_1.__importDefault(__webpack_require__(615)); -const manager_1 = tslib_1.__importDefault(__webpack_require__(253)); -const extensions_1 = tslib_1.__importDefault(__webpack_require__(342)); -const handler_1 = tslib_1.__importDefault(__webpack_require__(617)); -const languages_1 = tslib_1.__importDefault(__webpack_require__(505)); -const manager_2 = tslib_1.__importDefault(__webpack_require__(546)); -const services_1 = tslib_1.__importDefault(__webpack_require__(530)); -const manager_3 = tslib_1.__importDefault(__webpack_require__(337)); -const sources_1 = tslib_1.__importDefault(__webpack_require__(341)); -const types_1 = __webpack_require__(297); -const util_1 = __webpack_require__(238); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const logger = __webpack_require__(64)('plugin'); -class Plugin extends events_1.EventEmitter { - constructor(nvim) { - super(); - this.nvim = nvim; - this._ready = false; - this.actions = new Map(); - Object.defineProperty(workspace_1.default, 'nvim', { - get: () => this.nvim - }); - this.cursors = new cursors_1.default(nvim); - this.addAction('hasProvider', (id) => this.handler.hasProvider(id)); - this.addAction('getTagList', async () => await this.handler.getTagList()); - this.addAction('hasSelected', () => completion_1.default.hasSelected()); - this.addAction('listNames', () => manager_2.default.names); - this.addAction('listDescriptions', () => manager_2.default.descriptions); - this.addAction('listLoadItems', async (name) => await manager_2.default.loadItems(name)); - this.addAction('search', (...args) => this.handler.search(args)); - this.addAction('cursorsSelect', (bufnr, kind, mode) => this.cursors.select(bufnr, kind, mode)); - this.addAction('fillDiagnostics', (bufnr) => manager_1.default.setLocationlist(bufnr)); - this.addAction('getConfig', async (key) => { - let document = await workspace_1.default.document; - // eslint-disable-next-line id-blacklist - return workspace_1.default.getConfiguration(key, document ? document.uri : undefined); - }); - this.addAction('rootPatterns', bufnr => { - let doc = workspace_1.default.getDocument(bufnr); - if (!doc) - return null; - return { - buffer: workspace_1.default.getRootPatterns(doc, types_1.PatternType.Buffer), - server: workspace_1.default.getRootPatterns(doc, types_1.PatternType.LanguageServer), - global: workspace_1.default.getRootPatterns(doc, types_1.PatternType.Global) - }; - }); - this.addAction('installExtensions', async (...list) => { - await extensions_1.default.installExtensions(list); - }); - this.addAction('saveRefactor', async (bufnr) => { - await this.handler.saveRefactor(bufnr); - }); - this.addAction('updateExtensions', async (sync) => { - await extensions_1.default.updateExtensions(sync); - }); - this.addAction('commandList', () => commands_1.default.commandList.map(o => o.id)); - this.addAction('openList', async (...args) => { - await this.ready; - await manager_2.default.start(args); - }); - this.addAction('selectSymbolRange', (inner, visualmode, supportedSymbols) => this.handler.selectSymbolRange(inner, visualmode, supportedSymbols)); - this.addAction('listResume', (name) => manager_2.default.resume(name)); - this.addAction('listPrev', (name) => manager_2.default.previous(name)); - this.addAction('listNext', (name) => manager_2.default.next(name)); - this.addAction('listFirst', (name) => manager_2.default.first(name)); - this.addAction('listLast', (name) => manager_2.default.last(name)); - this.addAction('sendRequest', (id, method, params) => services_1.default.sendRequest(id, method, params)); - this.addAction('sendNotification', (id, method, params) => { - return services_1.default.sendNotification(id, method, params); - }); - this.addAction('registNotification', (id, method) => { - return services_1.default.registNotification(id, method); - }); - this.addAction('doAutocmd', async (id, ...args) => { - let autocmd = workspace_1.default.autocmds.get(id); - if (autocmd) { - try { - await Promise.resolve(autocmd.callback.apply(autocmd.thisArg, args)); - } - catch (e) { - logger.error(`Error on autocmd ${autocmd.event}`, e); - workspace_1.default.showMessage(`Error on autocmd ${autocmd.event}: ${e.message}`); - } - } - }); - this.addAction('updateConfig', (section, val) => { - workspace_1.default.configurations.updateUserConfig({ [section]: val }); - }); - this.addAction('snippetNext', async () => { - await manager_3.default.nextPlaceholder(); - return ''; - }); - this.addAction('snippetPrev', async () => { - await manager_3.default.previousPlaceholder(); - return ''; - }); - this.addAction('snippetCancel', () => { - manager_3.default.cancel(); - }); - this.addAction('openLocalConfig', async () => { - await workspace_1.default.openLocalConfig(); - }); - this.addAction('openLog', async () => { - let file = logger.getLogFile(); - await workspace_1.default.jumpTo(vscode_uri_1.URI.file(file).toString()); - }); - this.addAction('attach', () => { - return workspace_1.default.attach(); - }); - this.addAction('detach', () => { - return workspace_1.default.detach(); - }); - this.addAction('doKeymap', async (key, defaultReturn = '') => { - let keymap = workspace_1.default.keymaps.get(key); - if (!keymap) { - logger.error(`keymap for ${key} not found`); - return defaultReturn; - } - let [fn, repeat] = keymap; - let res = await Promise.resolve(fn()); - if (repeat) - await nvim.command(`silent! call repeat#set("\\(coc-${key})", -1)`); - return res || defaultReturn; - }); - this.addAction('registExtensions', async (...folders) => { - for (let folder of folders) { - await extensions_1.default.loadExtension(folder); - } - }); - this.addAction('snippetCheck', async (checkExpand, checkJump) => { - if (checkExpand && !extensions_1.default.has('coc-snippets')) { - console.error('coc-snippets required for check expand status!'); - return false; - } - if (checkJump) { - let jumpable = manager_3.default.jumpable(); - if (jumpable) - return true; - } - if (checkExpand) { - let api = extensions_1.default.getExtensionApi('coc-snippets'); - if (api && api.hasOwnProperty('expandable')) { - let expandable = await Promise.resolve(api.expandable()); - if (expandable) - return true; - } - } - return false; - }); - this.addAction('showInfo', async () => { - if (!this.infoChannel) { - this.infoChannel = workspace_1.default.createOutputChannel('info'); - } - else { - this.infoChannel.clear(); - } - let channel = this.infoChannel; - channel.appendLine('## versions'); - channel.appendLine(''); - let out = await this.nvim.call('execute', ['version']); - let first = out.trim().split('\n', 2)[0].replace(/\(.*\)/, '').trim(); - channel.appendLine('vim version: ' + first + `${workspace_1.default.isVim ? ' ' + workspace_1.default.env.version : ''}`); - channel.appendLine('node version: ' + process.version); - channel.appendLine('coc.nvim version: ' + this.version); - channel.appendLine('coc.nvim directory: ' + path_1.default.dirname(__dirname)); - channel.appendLine('term: ' + (process.env.TERM_PROGRAM || process.env.TERM)); - channel.appendLine('platform: ' + process.platform); - channel.appendLine(''); - channel.appendLine('## Log of coc.nvim'); - channel.appendLine(''); - let file = logger.getLogFile(); - if (fs_1.default.existsSync(file)) { - let content = fs_1.default.readFileSync(file, { encoding: 'utf8' }); - channel.appendLine(content); - } - channel.show(); - }); - this.addAction('findLocations', (id, method, params, openCommand) => { - return this.handler.findLocations(id, method, params, openCommand); - }); - this.addAction('links', () => { - return this.handler.links(); - }); - this.addAction('openLink', () => { - return this.handler.openLink(); - }); - this.addAction('pickColor', () => { - return this.handler.pickColor(); - }); - this.addAction('colorPresentation', () => { - return this.handler.pickPresentation(); - }); - this.addAction('highlight', async () => { - await this.handler.highlight(); - }); - this.addAction('fold', (kind) => { - return this.handler.fold(kind); - }); - this.addAction('startCompletion', async (option) => { - await completion_1.default.startCompletion(option); - }); - this.addAction('sourceStat', () => { - return sources_1.default.sourceStats(); - }); - this.addAction('refreshSource', async (name) => { - await sources_1.default.refresh(name); - }); - this.addAction('toggleSource', name => { - sources_1.default.toggleSource(name); - }); - this.addAction('diagnosticInfo', async () => { - await manager_1.default.echoMessage(); - }); - this.addAction('diagnosticToggle', () => { - manager_1.default.toggleDiagnostic(); - }); - this.addAction('diagnosticNext', async (severity) => { - await manager_1.default.jumpNext(severity); - }); - this.addAction('diagnosticPrevious', async (severity) => { - await manager_1.default.jumpPrevious(severity); - }); - this.addAction('diagnosticPreview', async () => { - await manager_1.default.preview(); - }); - this.addAction('diagnosticList', () => { - return manager_1.default.getDiagnosticList(); - }); - this.addAction('jumpDefinition', openCommand => { - return this.handler.gotoDefinition(openCommand); - }); - this.addAction('jumpDeclaration', openCommand => { - return this.handler.gotoDeclaration(openCommand); - }); - this.addAction('jumpImplementation', openCommand => { - return this.handler.gotoImplementation(openCommand); - }); - this.addAction('jumpTypeDefinition', openCommand => { - return this.handler.gotoTypeDefinition(openCommand); - }); - this.addAction('jumpReferences', openCommand => { - return this.handler.gotoReferences(openCommand); - }); - this.addAction('jumpUsed', openCommand => { - return this.handler.gotoReferences(openCommand, false); - }); - this.addAction('doHover', hoverTarget => { - return this.handler.onHover(hoverTarget); - }); - this.addAction('getHover', () => { - return this.handler.getHover(); - }); - this.addAction('showSignatureHelp', () => { - return this.handler.showSignatureHelp(); - }); - this.addAction('documentSymbols', async () => { - let doc = await workspace_1.default.document; - return await this.handler.getDocumentSymbols(doc); - }); - this.addAction('symbolRanges', () => { - return this.handler.getSymbolsRanges(); - }); - this.addAction('selectionRanges', () => { - return this.handler.getSelectionRanges(); - }); - this.addAction('rangeSelect', (visualmode, forward) => { - return this.handler.selectRange(visualmode, forward); - }); - this.addAction('rename', newName => { - return this.handler.rename(newName); - }); - this.addAction('getWorkspaceSymbols', async (input) => { - let tokenSource = new vscode_languageserver_protocol_1.CancellationTokenSource(); - return await languages_1.default.getWorkspaceSymbols(input, tokenSource.token); - }); - this.addAction('formatSelected', mode => { - return this.handler.documentRangeFormatting(mode); - }); - this.addAction('format', () => { - return this.handler.documentFormatting(); - }); - this.addAction('commands', () => { - return this.handler.getCommands(); - }); - this.addAction('services', () => { - return services_1.default.getServiceStats(); - }); - this.addAction('toggleService', name => { - return services_1.default.toggle(name); - }); - this.addAction('codeAction', (mode, only) => { - return this.handler.doCodeAction(mode, only); - }); - this.addAction('organizeImport', () => { - return this.handler.doCodeAction(null, [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]); - }); - this.addAction('fixAll', () => { - return this.handler.doCodeAction(null, [vscode_languageserver_protocol_1.CodeActionKind.SourceFixAll]); - }); - this.addAction('doCodeAction', codeAction => { - return this.handler.applyCodeAction(codeAction); - }); - this.addAction('codeActions', (mode, only) => { - return this.handler.getCurrentCodeActions(mode, only); - }); - this.addAction('quickfixes', mode => { - return this.handler.getCurrentCodeActions(mode, [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]); - }); - this.addAction('codeLensAction', () => { - return this.handler.doCodeLensAction(); - }); - this.addAction('runCommand', (...args) => { - return this.handler.runCommand(...args); - }); - this.addAction('doQuickfix', () => { - return this.handler.doQuickfix(); - }); - this.addAction('refactor', () => { - return this.handler.doRefactor(); - }); - this.addAction('repeatCommand', () => { - return commands_1.default.repeatCommand(); - }); - this.addAction('extensionStats', () => { - return extensions_1.default.getExtensionStates(); - }); - this.addAction('activeExtension', name => { - return extensions_1.default.activate(name); - }); - this.addAction('deactivateExtension', name => { - return extensions_1.default.deactivate(name); - }); - this.addAction('reloadExtension', name => { - return extensions_1.default.reloadExtension(name); - }); - this.addAction('toggleExtension', name => { - return extensions_1.default.toggleExtension(name); - }); - this.addAction('uninstallExtension', (...args) => { - return extensions_1.default.uninstallExtension(args); - }); - this.addAction('getCurrentFunctionSymbol', () => { - return this.handler.getCurrentFunctionSymbol(); - }); - this.addAction('getWordEdit', () => { - return this.handler.getWordEdit(); - }); - this.addAction('addRanges', async (ranges) => { - await this.cursors.addRanges(ranges); - }); - this.addAction('currentWorkspacePath', () => { - return workspace_1.default.rootPath; - }); - this.addAction('addCommand', cmd => { - this.addCommand(cmd); - }); - this.addAction('selectCurrentPlaceholder', (triggerAutocmd) => { - return manager_3.default.selectCurrentPlaceholder(!!triggerAutocmd); - }); - this.addAction('codeActionRange', (start, end, only) => this.handler.codeActionRange(start, end, only)); - workspace_1.default.onDidChangeWorkspaceFolders(() => { - nvim.setVar('WorkspaceFolders', workspace_1.default.folderPaths, true); - }); - commands_1.default.init(nvim, this); - } - addAction(key, fn) { - if (this.actions.has(key)) { - throw new Error(`Action ${key} already exists`); - } - this.actions.set(key, fn); - } - addCommand(cmd) { - let id = `vim.${cmd.id}`; - commands_1.default.registerCommand(id, async () => { - await this.nvim.command(cmd.cmd); - }); - if (cmd.title) - commands_1.default.titles.set(id, cmd.title); - } - async init() { - let { nvim } = this; - let s = Date.now(); - try { - await extensions_1.default.init(); - await workspace_1.default.init(); - for (let item of workspace_1.default.env.vimCommands) { - this.addCommand(item); - } - manager_3.default.init(); - completion_1.default.init(); - manager_1.default.init(); - manager_2.default.init(nvim); - nvim.setVar('coc_workspace_initialized', 1, true); - nvim.setVar('WorkspaceFolders', workspace_1.default.folderPaths, true); - sources_1.default.init(); - this.handler = new handler_1.default(nvim); - services_1.default.init(); - await extensions_1.default.activateExtensions(); - workspace_1.default.setupDynamicAutocmd(true); - nvim.setVar('coc_service_initialized', 1, true); - nvim.call('coc#util#do_autocmd', ['CocNvimInit'], true); - this._ready = true; - logger.info(`coc.nvim ${this.version} initialized with node: ${process.version} after ${Date.now() - s}ms`); - this.emit('ready'); - } - catch (e) { - console.error(`Error on initialize: ${e.stack}`); - logger.error(e.stack); - } - workspace_1.default.onDidOpenTextDocument(async (doc) => { - if (!doc.uri.endsWith(util_1.CONFIG_FILE_NAME)) - return; - if (extensions_1.default.has('coc-json')) - return; - workspace_1.default.showMessage(`Run :CocInstall coc-json for json intellisense`, 'more'); - }); - } - get isReady() { - return this._ready; - } - get ready() { - if (this._ready) - return Promise.resolve(); - return new Promise(resolve => { - this.once('ready', () => { - resolve(); - }); - }); - } - get version() { - return workspace_1.default.version + ( true ? '-' + "8230b63641" : undefined); - } - hasAction(method) { - return this.actions.has(method); - } - async cocAction(method, ...args) { - let fn = this.actions.get(method); - return await Promise.resolve(fn.apply(null, args)); - } - dispose() { - this.removeAllListeners(); - extensions_1.default.dispose(); - manager_2.default.dispose(); - workspace_1.default.dispose(); - sources_1.default.dispose(); - services_1.default.stopAll(); - services_1.default.dispose(); - if (this.handler) { - this.handler.dispose(); - } - manager_3.default.dispose(); - commands_1.default.dispose(); - completion_1.default.dispose(); - manager_1.default.dispose(); - } -} -exports.default = Plugin; -//# sourceMappingURL=plugin.js.map - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CommandManager = void 0; -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const manager_1 = tslib_1.__importDefault(__webpack_require__(253)); -const manager_2 = tslib_1.__importDefault(__webpack_require__(337)); -const util_1 = __webpack_require__(238); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const logger = __webpack_require__(64)('commands'); -class CommandItem { - constructor(id, impl, thisArg, internal = false) { - this.id = id; - this.impl = impl; - this.thisArg = thisArg; - this.internal = internal; - } - execute(...args) { - let { impl, thisArg } = this; - return impl.apply(thisArg, args || []); - } - dispose() { - this.thisArg = null; - this.impl = null; - } -} -class CommandManager { - constructor() { - this.commands = new Map(); - this.titles = new Map(); - } - init(nvim, plugin) { - this.mru = workspace_1.default.createMru('commands'); - this.register({ - id: 'vscode.open', - execute: async (url) => { - nvim.call('coc#util#open_url', url.toString(), true); - } - }, true); - this.register({ - id: 'workbench.action.reloadWindow', - execute: () => { - nvim.command('CocRestart', true); - } - }, true); - this.register({ - id: 'editor.action.insertSnippet', - execute: async (edit) => { - let doc = workspace_1.default.getDocument(workspace_1.default.bufnr); - if (!doc) - return; - await nvim.call('coc#_cancel', []); - if (doc.dirty) - doc.forceSync(); - await manager_2.default.insertSnippet(edit.newText, true, edit.range); - } - }, true); - this.register({ - id: 'editor.action.doCodeAction', - execute: async (action) => { - await plugin.cocAction('doCodeAction', action); - } - }, true); - this.register({ - id: 'editor.action.triggerSuggest', - execute: async () => { - await util_1.wait(100); - nvim.call('coc#start', [], true); - } - }, true); - this.register({ - id: 'editor.action.triggerParameterHints', - execute: async () => { - await util_1.wait(60); - await plugin.cocAction('showSignatureHelp'); - } - }, true); - this.register({ - id: 'editor.action.addRanges', - execute: async (ranges) => { - await plugin.cocAction('addRanges', ranges); - } - }, true); - this.register({ - id: 'editor.action.restart', - execute: async () => { - await util_1.wait(30); - nvim.command('CocRestart', true); - } - }, true); - this.register({ - id: 'editor.action.showReferences', - execute: async (_filepath, _position, references) => { - await workspace_1.default.showLocations(references); - } - }, true); - this.register({ - id: 'editor.action.rename', - execute: async (uri, position) => { - await workspace_1.default.jumpTo(uri, position); - await plugin.cocAction('rename'); - } - }, true); - this.register({ - id: 'editor.action.format', - execute: async () => { - await plugin.cocAction('format'); - } - }, true); - this.register({ - id: 'workspace.diffDocument', - execute: async () => { - let document = await workspace_1.default.document; - if (!document) - return; - await nvim.call('coc#util#diff_content', [document.getLines()]); - } - }); - this.register({ - id: 'workspace.clearWatchman', - execute: async () => { - if (global.hasOwnProperty('__TEST__')) - return; - let res = await workspace_1.default.runTerminalCommand('watchmann watch-del-all'); - if (res.success) - workspace_1.default.showMessage('Cleared watchman watching directories.'); - } - }, false, 'run watch-del-all for watchman to free up memory.'); - this.register({ - id: 'workspace.workspaceFolders', - execute: async () => { - let folders = workspace_1.default.workspaceFolders; - let lines = folders.map(folder => vscode_uri_1.URI.parse(folder.uri).fsPath); - await workspace_1.default.echoLines(lines); - } - }, false, 'show opened workspaceFolders.'); - this.register({ - id: 'workspace.renameCurrentFile', - execute: async () => { - await workspace_1.default.renameCurrent(); - } - }, false, 'change current filename to a new name and reload it.'); - this.register({ - id: 'extensions.toggleAutoUpdate', - execute: async () => { - let config = workspace_1.default.getConfiguration('coc.preferences'); - let interval = config.get('extensionUpdateCheck', 'daily'); - if (interval == 'never') { - config.update('extensionUpdateCheck', 'daily', true); - workspace_1.default.showMessage('Extension auto update enabled.', 'more'); - } - else { - config.update('extensionUpdateCheck', 'never', true); - workspace_1.default.showMessage('Extension auto update disabled.', 'more'); - } - } - }, false, 'toggle auto update of extensions.'); - this.register({ - id: 'workspace.diagnosticRelated', - execute: () => manager_1.default.jumpRelated() - }, false, 'jump to related locations of current diagnostic.'); - this.register({ - id: 'workspace.showOutput', - execute: async (name) => { - if (name) { - workspace_1.default.showOutputChannel(name); - } - else { - let names = workspace_1.default.channelNames; - if (names.length == 0) - return; - if (names.length == 1) { - workspace_1.default.showOutputChannel(names[0]); - } - else { - let idx = await workspace_1.default.showQuickpick(names); - if (idx == -1) - return; - let name = names[idx]; - workspace_1.default.showOutputChannel(name); - } - } - } - }, false, 'open output buffer to show output from languageservers or extensions.'); - this.register({ - id: 'document.echoFiletype', - execute: async () => { - let bufnr = await nvim.call('bufnr', '%'); - let doc = workspace_1.default.getDocument(bufnr); - if (!doc) - return; - await workspace_1.default.echoLines([doc.filetype]); - } - }, false, 'echo the mapped filetype of the current buffer'); - this.register({ - id: 'document.renameCurrentWord', - execute: async () => { - let bufnr = await nvim.call('bufnr', '%'); - let doc = workspace_1.default.getDocument(bufnr); - if (!doc) - return; - let edit = await plugin.cocAction('getWordEdit'); - if (!edit) { - workspace_1.default.showMessage('Invalid position', 'warning'); - return; - } - let ranges = []; - let { changes, documentChanges } = edit; - if (changes) { - let edits = changes[doc.uri]; - if (edits) - ranges = edits.map(e => e.range); - } - else if (documentChanges) { - for (let c of documentChanges) { - if (vscode_languageserver_protocol_1.TextDocumentEdit.is(c) && c.textDocument.uri == doc.uri) { - ranges = c.edits.map(e => e.range); - } - } - } - if (ranges.length) { - await plugin.cocAction('addRanges', ranges); - } - } - }, false, 'rename word under cursor in current buffer by use multiple cursors.'); - this.register({ - id: 'document.jumpToNextSymbol', - execute: async () => { - let doc = await workspace_1.default.document; - if (!doc) - return; - let ranges = await plugin.cocAction('symbolRanges'); - if (!ranges) - return; - let { textDocument } = doc; - let offset = await workspace_1.default.getOffset(); - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - for (let i = 0; i <= ranges.length - 1; i++) { - if (textDocument.offsetAt(ranges[i].start) > offset) { - await workspace_1.default.moveTo(ranges[i].start); - return; - } - } - await workspace_1.default.moveTo(ranges[0].start); - } - }, false, 'Jump to next symbol highlight position.'); - this.register({ - id: 'document.jumpToPrevSymbol', - execute: async () => { - let doc = await workspace_1.default.document; - if (!doc) - return; - let ranges = await plugin.cocAction('symbolRanges'); - if (!ranges) - return; - let { textDocument } = doc; - let offset = await workspace_1.default.getOffset(); - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - for (let i = ranges.length - 1; i >= 0; i--) { - if (textDocument.offsetAt(ranges[i].end) < offset) { - await workspace_1.default.moveTo(ranges[i].start); - return; - } - } - await workspace_1.default.moveTo(ranges[ranges.length - 1].start); - } - }, false, 'Jump to previous symbol highlight position.'); - } - get commandList() { - let res = []; - for (let item of this.commands.values()) { - if (!item.internal) - res.push(item); - } - return res; - } - dispose() { - for (const registration of this.commands.values()) { - registration.dispose(); - } - this.commands.clear(); - } - execute(command) { - let args = [command.command]; - let arr = command.arguments; - if (arr) - args.push(...arr); - this.executeCommand.apply(this, args); - } - register(command, internal = false, description) { - for (const id of Array.isArray(command.id) ? command.id : [command.id]) { - this.registerCommand(id, command.execute, command, internal); - if (description) - this.titles.set(id, description); - } - return command; - } - has(id) { - return this.commands.has(id); - } - unregister(id) { - let item = this.commands.get(id); - if (!item) - return; - item.dispose(); - this.commands.delete(id); - } - /** - * Registers a command that can be invoked via a keyboard shortcut, - * a menu item, an action, or directly. - * - * Registering a command with an existing command identifier twice - * will cause an error. - * - * @param command A unique identifier for the command. - * @param impl A command handler function. - * @param thisArg The `this` context used when invoking the handler function. - * @return Disposable which unregisters this command on disposal. - */ - registerCommand(id, impl, thisArg, internal = false) { - if (id.startsWith("_")) - internal = true; - this.commands.set(id, new CommandItem(id, impl, thisArg, internal)); - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.commands.delete(id); - }); - } - /** - * Executes the command denoted by the given command identifier. - * - * * *Note 1:* When executing an editor command not all types are allowed to - * be passed as arguments. Allowed are the primitive types `string`, `boolean`, - * `number`, `undefined`, and `null`, as well as [`Position`](#Position), [`Range`](#Range), [`URI`](#URI) and [`Location`](#Location). - * * *Note 2:* There are no restrictions when executing commands that have been contributed - * by extensions. - * - * @param command Identifier of the command to execute. - * @param rest Parameters passed to the command function. - * @return A promise that resolves to the returned value of the given command. `undefined` when - * the command handler function doesn't return anything. - */ - executeCommand(command, ...rest) { - let cmd = this.commands.get(command); - if (!cmd) { - workspace_1.default.showMessage(`Command: ${command} not found`, 'error'); - return; - } - return Promise.resolve(cmd.execute.apply(cmd, rest)).catch(e => { - workspace_1.default.showMessage(`Command error: ${e.message}`, 'error'); - logger.error(e.stack); - }); - } - async addRecent(cmd) { - await this.mru.add(cmd); - await workspace_1.default.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`); - } - async repeatCommand() { - let mruList = await this.mru.load(); - let first = mruList[0]; - if (first) { - await this.executeCommand(first); - await workspace_1.default.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`); - } - } -} -exports.CommandManager = CommandManager; -exports.default = new CommandManager(); -//# sourceMappingURL=commands.js.map - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagnosticManager = void 0; -const tslib_1 = __webpack_require__(65); -const debounce_1 = tslib_1.__importDefault(__webpack_require__(240)); -const semver_1 = tslib_1.__importDefault(__webpack_require__(1)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const floatFactory_1 = tslib_1.__importDefault(__webpack_require__(254)); -const util_1 = __webpack_require__(238); -const position_1 = __webpack_require__(315); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const buffer_1 = __webpack_require__(334); -const collection_1 = tslib_1.__importDefault(__webpack_require__(336)); -const util_2 = __webpack_require__(335); -const logger = __webpack_require__(64)('diagnostic-manager'); -class DiagnosticManager { - constructor() { - this.enabled = true; - this.buffers = new Map(); - this.lastMessage = ''; - this.collections = []; - this.disposables = []; - } - init() { - this.setConfiguration(); - let { nvim } = workspace_1.default; - let { maxWindowHeight, maxWindowWidth } = this.config; - this.floatFactory = new floatFactory_1.default(nvim, workspace_1.default.env, false, maxWindowHeight, maxWindowWidth); - this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - if (this.timer) - clearTimeout(this.timer); - })); - events_1.default.on('CursorMoved', () => { - if (this.config.enableMessage != 'always') - return; - if (this.timer) - clearTimeout(this.timer); - this.timer = setTimeout(async () => { - await this.echoMessage(true); - }, this.config.messageDelay); - }, null, this.disposables); - let fn = debounce_1.default((bufnr, cursor) => { - if (!this.config.virtualText || !this.config.virtualTextCurrentLineOnly) { - return; - } - let buf = this.buffers.get(bufnr); - if (buf) { - let diagnostics = this.getDiagnostics(buf.uri); - buf.showVirtualText(diagnostics, cursor[0]); - } - }, 100); - events_1.default.on('CursorMoved', fn, null, this.disposables); - this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - fn.clear(); - })); - events_1.default.on('InsertEnter', () => { - if (this.timer) - clearTimeout(this.timer); - this.floatFactory.close(); - }, null, this.disposables); - events_1.default.on('InsertLeave', async (bufnr) => { - this.floatFactory.close(); - if (!this.buffers.has(bufnr)) - return; - let doc = workspace_1.default.getDocument(bufnr); - if (!doc) - return; - doc.forceSync(); - let { refreshOnInsertMode, refreshAfterSave } = this.config; - if (!refreshOnInsertMode && !refreshAfterSave) { - this.refreshBuffer(doc.uri); - } - }, null, this.disposables); - events_1.default.on('BufEnter', async () => { - if (this.timer) - clearTimeout(this.timer); - }, null, this.disposables); - events_1.default.on('BufWritePost', async (bufnr) => { - let buf = this.buffers.get(bufnr); - if (!buf) - return; - await buf.checkSigns(); - if (!this.config.refreshAfterSave) - return; - this.refreshBuffer(buf.uri); - }, null, this.disposables); - workspace_1.default.onDidChangeConfiguration(e => { - this.setConfiguration(e); - }, null, this.disposables); - // create buffers - for (let doc of workspace_1.default.documents) { - this.createDiagnosticBuffer(doc); - } - workspace_1.default.onDidOpenTextDocument(textDocument => { - let doc = workspace_1.default.getDocument(textDocument.uri); - this.createDiagnosticBuffer(doc); - }, null, this.disposables); - workspace_1.default.onDidCloseTextDocument(({ uri }) => { - let doc = workspace_1.default.getDocument(uri); - if (!doc) - return; - this.disposeBuffer(doc.bufnr); - }, null, this.disposables); - this.setConfigurationErrors(true); - workspace_1.default.configurations.onError(() => { - this.setConfigurationErrors(); - }, null, this.disposables); - let { enableHighlightLineNumber } = this.config; - if (!workspace_1.default.isNvim || semver_1.default.lt(workspace_1.default.env.version, 'v0.3.2')) { - enableHighlightLineNumber = false; - } - nvim.pauseNotification(); - if (this.config.enableSign) { - for (let kind of ['Error', 'Warning', 'Info', 'Hint']) { - let signText = this.config[kind.toLowerCase() + 'Sign']; - let cmd = `sign define Coc${kind} linehl=Coc${kind}Line`; - if (signText) - cmd += ` texthl=Coc${kind}Sign text=${signText}`; - if (enableHighlightLineNumber) - cmd += ` numhl=Coc${kind}Sign`; - nvim.command(cmd, true); - } - } - nvim.resumeNotification(false, true).logError(); - } - createDiagnosticBuffer(doc) { - if (!this.shouldValidate(doc)) - return; - let { bufnr } = doc; - let buf = this.buffers.get(bufnr); - if (buf) - return; - buf = new buffer_1.DiagnosticBuffer(bufnr, doc.uri, this.config); - this.buffers.set(bufnr, buf); - buf.onDidRefresh(() => { - if (['never', 'jump'].includes(this.config.enableMessage)) { - return; - } - this.echoMessage(true).logError(); - }); - } - async setLocationlist(bufnr) { - let buf = this.buffers.get(bufnr); - let diagnostics = buf ? this.getDiagnostics(buf.uri) : []; - let items = []; - for (let diagnostic of diagnostics) { - let item = util_2.getLocationListItem(bufnr, diagnostic); - items.push(item); - } - let curr = await this.nvim.call('getloclist', [0, { title: 1 }]); - let action = curr.title && curr.title.indexOf('Diagnostics of coc') != -1 ? 'r' : ' '; - await this.nvim.call('setloclist', [0, [], action, { title: 'Diagnostics of coc', items }]); - } - setConfigurationErrors(init) { - let collections = this.collections; - let collection = collections.find(o => o.name == 'config'); - if (!collection) { - collection = this.create('config'); - } - else { - collection.clear(); - } - let { errorItems } = workspace_1.default.configurations; - if (errorItems && errorItems.length) { - if (init) - workspace_1.default.showMessage(`settings file parse error, run ':CocList diagnostics'`, 'error'); - let entries = new Map(); - for (let item of errorItems) { - let { uri } = item.location; - let diagnostics = entries.get(uri) || []; - diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(item.location.range, item.message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error)); - entries.set(uri, diagnostics); - } - collection.set(Array.from(entries)); - } - } - /** - * Create collection by name - */ - create(name) { - let collection = new collection_1.default(name); - this.collections.push(collection); - // Used for refresh diagnostics on buferEnter when refreshAfterSave is true - // Note we can't make sure it work as expected when there're multiple sources - let createTime = Date.now(); - let refreshed = false; - collection.onDidDiagnosticsChange(uri => { - if (this.config.refreshAfterSave && - (refreshed || Date.now() - createTime > 5000)) - return; - refreshed = true; - this.refreshBuffer(uri); - }); - collection.onDidDiagnosticsClear(uris => { - for (let uri of uris) { - this.refreshBuffer(uri, true); - } - }); - collection.onDispose(() => { - let idx = this.collections.findIndex(o => o == collection); - if (idx !== -1) - this.collections.splice(idx, 1); - }); - return collection; - } - /** - * Get diagnostics ranges from document - */ - getSortedRanges(uri, severity) { - let collections = this.getCollections(uri); - let res = []; - let level = severity ? util_2.severityLevel(severity) : 0; - for (let collection of collections) { - let diagnostics = collection.get(uri); - if (level) - diagnostics = diagnostics.filter(o => o.severity == level); - let ranges = diagnostics.map(o => o.range); - res.push(...ranges); - } - res.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - return res; - } - /** - * Get readonly diagnostics for a buffer - */ - getDiagnostics(uri) { - let collections = this.getCollections(uri); - let { level } = this.config; - let res = []; - for (let collection of collections) { - let items = collection.get(uri); - if (!items) - continue; - if (level && level < vscode_languageserver_protocol_1.DiagnosticSeverity.Hint) { - items = items.filter(s => s.severity == null || s.severity <= level); - } - res.push(...items); - } - res.sort((a, b) => { - if (a.severity == b.severity) { - let d = position_1.comparePosition(a.range.start, b.range.start); - if (d != 0) - return d; - if (a.source == b.source) - return a.message > b.message ? 1 : -1; - return a.source > b.source ? 1 : -1; - } - return a.severity - b.severity; - }); - return res; - } - getDiagnosticsInRange(document, range) { - let collections = this.getCollections(document.uri); - let res = []; - for (let collection of collections) { - let items = collection.get(document.uri); - if (!items) - continue; - for (let item of items) { - if (position_1.rangeIntersect(item.range, range)) { - res.push(item); - } - } - } - return res; - } - /** - * Show diagnostics under curosr in preview window - */ - async preview() { - let [bufnr, cursor] = await this.nvim.eval('[bufnr("%"),coc#util#cursor()]'); - let { nvim } = this; - let diagnostics = this.getDiagnosticsAt(bufnr, cursor); - if (diagnostics.length == 0) { - nvim.command('pclose', true); - workspace_1.default.showMessage(`Empty diagnostics`, 'warning'); - return; - } - let lines = []; - for (let diagnostic of diagnostics) { - let { source, code, severity, message } = diagnostic; - let s = util_2.getSeverityName(severity)[0]; - lines.push(`[${source}${code ? ' ' + code : ''}] [${s}]`); - lines.push(...message.split(/\r?\n/)); - lines.push(''); - } - lines = lines.slice(0, -1); - // let content = lines.join('\n').trim() - nvim.call('coc#util#preview_info', [lines, 'txt'], true); - } - /** - * Jump to previous diagnostic position - */ - async jumpPrevious(severity) { - let buffer = await this.nvim.buffer; - let document = workspace_1.default.getDocument(buffer.id); - if (!document) - return; - let offset = await workspace_1.default.getOffset(); - if (offset == null) - return; - let ranges = this.getSortedRanges(document.uri, severity); - if (ranges.length == 0) { - workspace_1.default.showMessage('Empty diagnostics', 'warning'); - return; - } - let { textDocument } = document; - let pos; - for (let i = ranges.length - 1; i >= 0; i--) { - if (textDocument.offsetAt(ranges[i].end) < offset) { - pos = ranges[i].start; - break; - } - else if (i == 0) { - let wrapscan = await this.nvim.getOption('wrapscan'); - if (wrapscan) - pos = ranges[ranges.length - 1].start; - } - } - if (pos) { - await workspace_1.default.moveTo(pos); - if (this.config.enableMessage == 'never') - return; - await this.echoMessage(false); - } - } - /** - * Jump to next diagnostic position - */ - async jumpNext(severity) { - let buffer = await this.nvim.buffer; - let document = workspace_1.default.getDocument(buffer.id); - let offset = await workspace_1.default.getOffset(); - let ranges = this.getSortedRanges(document.uri, severity); - if (ranges.length == 0) { - workspace_1.default.showMessage('Empty diagnostics', 'warning'); - return; - } - let { textDocument } = document; - let pos; - for (let i = 0; i <= ranges.length - 1; i++) { - if (textDocument.offsetAt(ranges[i].start) > offset) { - pos = ranges[i].start; - break; - } - else if (i == ranges.length - 1) { - let wrapscan = await this.nvim.getOption('wrapscan'); - if (wrapscan) - pos = ranges[0].start; - } - } - if (pos) { - await workspace_1.default.moveTo(pos); - if (this.config.enableMessage == 'never') - return; - await this.echoMessage(false); - } - } - /** - * All diagnostics of current workspace - */ - getDiagnosticList() { - let res = []; - const { level } = this.config; - for (let collection of this.collections) { - collection.forEach((uri, diagnostics) => { - let file = vscode_uri_1.URI.parse(uri).fsPath; - for (let diagnostic of diagnostics) { - if (diagnostic.severity && diagnostic.severity > level) { - continue; - } - let { start } = diagnostic.range; - let o = { - file, - lnum: start.line + 1, - col: start.character + 1, - message: `[${diagnostic.source || collection.name}${diagnostic.code ? ' ' + diagnostic.code : ''}] ${diagnostic.message}`, - severity: util_2.getSeverityName(diagnostic.severity), - level: diagnostic.severity || 0, - location: vscode_languageserver_protocol_1.Location.create(uri, diagnostic.range) - }; - res.push(o); - } - }); - } - res.sort((a, b) => { - if (a.level !== b.level) { - return a.level - b.level; - } - if (a.file !== b.file) { - return a.file > b.file ? 1 : -1; - } - else { - if (a.lnum != b.lnum) { - return a.lnum - b.lnum; - } - return a.col - b.col; - } - }); - return res; - } - getDiagnosticsAt(bufnr, cursor) { - let pos = vscode_languageserver_protocol_1.Position.create(cursor[0], cursor[1]); - let buffer = this.buffers.get(bufnr); - if (!buffer) - return []; - let diagnostics = this.getDiagnostics(buffer.uri); - let { checkCurrentLine } = this.config; - if (checkCurrentLine) { - diagnostics = diagnostics.filter(o => position_1.lineInRange(pos.line, o.range)); - } - else { - diagnostics = diagnostics.filter(o => position_1.positionInRange(pos, o.range) == 0); - } - diagnostics.sort((a, b) => a.severity - b.severity); - return diagnostics; - } - async getCurrentDiagnostics() { - let [bufnr, cursor] = await this.nvim.eval('[bufnr("%"),coc#util#cursor()]'); - return this.getDiagnosticsAt(bufnr, cursor); - } - /** - * Echo diagnostic message of currrent position - */ - async echoMessage(truncate = false) { - const config = this.config; - if (!this.enabled) - return; - if (this.timer) - clearTimeout(this.timer); - let useFloat = config.messageTarget == 'float'; - let [bufnr, cursor, filetype, mode, disabled, isFloat] = await this.nvim.eval('[bufnr("%"),coc#util#cursor(),&filetype,mode(),get(b:,"coc_diagnostic_disable",0),get(w:,"float",0)]'); - if (mode != 'n' || isFloat == 1 || disabled) - return; - let diagnostics = this.getDiagnosticsAt(bufnr, cursor); - if (diagnostics.length == 0) { - if (useFloat) { - this.floatFactory.close(); - } - else { - let echoLine = await this.nvim.call('coc#util#echo_line'); - if (this.lastMessage && echoLine.startsWith(this.lastMessage)) { - this.nvim.command('echo ""', true); - } - } - return; - } - if (truncate && workspace_1.default.insertMode) - return; - let docs = []; - let ft = ''; - if (Object.keys(config.filetypeMap).length > 0) { - const defaultFiletype = config.filetypeMap['default'] || ''; - ft = config.filetypeMap[filetype] || (defaultFiletype == 'bufferType' ? filetype : defaultFiletype); - } - diagnostics.forEach(diagnostic => { - let { source, code, severity, message } = diagnostic; - let s = util_2.getSeverityName(severity)[0]; - const codeStr = code ? ' ' + code : ''; - const str = config.format.replace('%source', source).replace('%code', codeStr).replace('%severity', s).replace('%message', message); - let filetype = 'Error'; - if (ft === '') { - switch (severity) { - case vscode_languageserver_protocol_1.DiagnosticSeverity.Hint: - filetype = 'Hint'; - break; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Warning: - filetype = 'Warning'; - break; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Information: - filetype = 'Info'; - break; - } - } - else { - filetype = ft; - } - docs.push({ filetype, content: str }); - }); - if (useFloat) { - await this.floatFactory.show(docs); - } - else { - let lines = docs.map(d => d.content).join('\n').split(/\r?\n/); - if (lines.length) { - await this.nvim.command('echo ""'); - this.lastMessage = lines[0].slice(0, 30); - await workspace_1.default.echoLines(lines, truncate); - } - } - } - async jumpRelated() { - let diagnostics = await this.getCurrentDiagnostics(); - if (!diagnostics) - return; - let diagnostic = diagnostics.find(o => o.relatedInformation != null); - if (!diagnostic) - return; - let locations = diagnostic.relatedInformation.map(o => o.location); - if (locations.length == 1) { - await workspace_1.default.jumpTo(locations[0].uri, locations[0].range.start); - } - else if (locations.length > 1) { - await workspace_1.default.showLocations(locations); - } - } - disposeBuffer(bufnr) { - let buf = this.buffers.get(bufnr); - if (!buf) - return; - buf.clear().logError(); - buf.dispose(); - this.buffers.delete(bufnr); - for (let collection of this.collections) { - collection.delete(buf.uri); - } - } - hideFloat() { - if (this.floatFactory) { - this.floatFactory.close(); - } - } - dispose() { - for (let buf of this.buffers.values()) { - buf.clear().logError(); - buf.dispose(); - } - for (let collection of this.collections) { - collection.dispose(); - } - this.hideFloat(); - this.buffers.clear(); - this.collections = []; - util_1.disposeAll(this.disposables); - } - get nvim() { - return workspace_1.default.nvim; - } - setConfiguration(event) { - if (event && !event.affectsConfiguration('diagnostic')) - return; - let config = workspace_1.default.getConfiguration('diagnostic'); - let messageTarget = config.get('messageTarget', 'float'); - if (messageTarget == 'float' && !workspace_1.default.env.floating && !workspace_1.default.env.textprop) { - messageTarget = 'echo'; - } - this.config = { - messageTarget, - srcId: workspace_1.default.createNameSpace('coc-diagnostic') || 1000, - virtualTextSrcId: workspace_1.default.createNameSpace('diagnostic-virtualText'), - checkCurrentLine: config.get('checkCurrentLine', false), - enableSign: config.get('enableSign', true), - locationlistUpdate: config.get('locationlistUpdate', true), - enableHighlightLineNumber: config.get('enableHighlightLineNumber', true), - maxWindowHeight: config.get('maxWindowHeight', 10), - maxWindowWidth: config.get('maxWindowWidth', 80), - enableMessage: config.get('enableMessage', 'always'), - messageDelay: config.get('messageDelay', 200), - virtualText: config.get('virtualText', false) && this.nvim.hasFunction('nvim_buf_set_virtual_text'), - virtualTextCurrentLineOnly: config.get('virtualTextCurrentLineOnly', true), - virtualTextPrefix: config.get('virtualTextPrefix', " "), - virtualTextLineSeparator: config.get('virtualTextLineSeparator', " \\ "), - virtualTextLines: config.get('virtualTextLines', 3), - displayByAle: config.get('displayByAle', false), - level: util_2.severityLevel(config.get('level', 'hint')), - signOffset: config.get('signOffset', 1000), - errorSign: config.get('errorSign', '>>'), - warningSign: config.get('warningSign', '>>'), - infoSign: config.get('infoSign', '>>'), - hintSign: config.get('hintSign', '>>'), - refreshAfterSave: config.get('refreshAfterSave', false), - refreshOnInsertMode: config.get('refreshOnInsertMode', false), - filetypeMap: config.get('filetypeMap', {}), - format: config.get('format', '[%source%code] [%severity] %message') - }; - this.enabled = config.get('enable', true); - if (this.config.displayByAle) { - this.enabled = false; - } - if (event) { - for (let severity of ['error', 'info', 'warning', 'hint']) { - let key = `diagnostic.${severity}Sign`; - if (event.affectsConfiguration(key)) { - let text = config.get(`${severity}Sign`, '>>'); - let name = severity[0].toUpperCase() + severity.slice(1); - this.nvim.command(`sign define Coc${name} text=${text} linehl=Coc${name}Line texthl=Coc${name}Sign`, true); - } - } - } - } - getCollections(uri) { - return this.collections.filter(c => c.has(uri)); - } - shouldValidate(doc) { - return doc != null && doc.buftype == '' && doc.attached; - } - clearDiagnostic(bufnr) { - let buf = this.buffers.get(bufnr); - if (!buf) - return; - for (let collection of this.collections) { - collection.delete(buf.uri); - } - buf.clear().logError(); - } - toggleDiagnostic() { - let { enabled } = this; - this.enabled = !enabled; - for (let buf of this.buffers.values()) { - if (this.enabled) { - let diagnostics = this.getDiagnostics(buf.uri); - buf.forceRefresh(diagnostics); - } - else { - buf.clear().logError(); - } - } - } - refreshBuffer(uri, force = false) { - let buf = Array.from(this.buffers.values()).find(o => o.uri == uri); - if (!buf) - return false; - let { displayByAle, refreshOnInsertMode } = this.config; - if (!refreshOnInsertMode && workspace_1.default.insertMode) - return false; - if (!displayByAle) { - let diagnostics = this.getDiagnostics(uri); - if (this.enabled) { - if (force) { - buf.forceRefresh(diagnostics); - } - else { - buf.refresh(diagnostics); - } - return true; - } - } - else { - let { nvim } = this; - nvim.pauseNotification(); - for (let collection of this.collections) { - let diagnostics = collection.get(uri); - const { level } = this.config; - if (level) { - diagnostics = diagnostics.filter(o => o.severity && o.severity <= level); - } - let aleItems = diagnostics.map(o => { - let { range } = o; - return { - text: o.message, - code: o.code, - lnum: range.start.line + 1, - col: range.start.character + 1, - end_lnum: range.end.line + 1, - end_col: range.end.character, - type: util_2.getSeverityType(o.severity) - }; - }); - nvim.call('ale#other_source#ShowResults', [buf.bufnr, collection.name, aleItems], true); - } - nvim.resumeNotification(false, true).logError(); - } - return false; - } -} -exports.DiagnosticManager = DiagnosticManager; -exports.default = new DiagnosticManager(); -//# sourceMappingURL=manager.js.map - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const debounce_1 = tslib_1.__importDefault(__webpack_require__(240)); -const events_1 = __webpack_require__(198); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const events_2 = tslib_1.__importDefault(__webpack_require__(210)); -const util_1 = __webpack_require__(238); -const mutex_1 = __webpack_require__(255); -const object_1 = __webpack_require__(249); -const floatBuffer_1 = tslib_1.__importDefault(__webpack_require__(256)); -const logger = __webpack_require__(64)('model-float'); -// factory class for floating window -class FloatFactory extends events_1.EventEmitter { - constructor(nvim, env, preferTop = false, maxHeight = 999, maxWidth, autoHide = true) { - super(); - this.nvim = nvim; - this.env = env; - this.preferTop = preferTop; - this.maxHeight = maxHeight; - this.maxWidth = maxWidth; - this.autoHide = autoHide; - this.winid = 0; - this._bufnr = 0; - this.disposables = []; - this.alignTop = false; - this.pumAlignTop = false; - this.mutex = new mutex_1.Mutex(); - this.floatBuffer = new floatBuffer_1.default(nvim); - events_2.default.on('BufEnter', bufnr => { - if (bufnr == this._bufnr - || bufnr == this.targetBufnr) - return; - this.close(); - }, null, this.disposables); - events_2.default.on('InsertEnter', bufnr => { - if (bufnr == this._bufnr) - return; - this.close(); - }); - events_2.default.on('MenuPopupChanged', (ev, cursorline) => { - let pumAlignTop = this.pumAlignTop = cursorline > ev.row; - if (pumAlignTop == this.alignTop) { - this.close(); - } - }, null, this.disposables); - events_2.default.on('BufWinLeave', bufnr => { - if (this.bufnr == bufnr) { - this.emit('close'); - } - }, null, this.disposables); - this.onCursorMoved = debounce_1.default(this._onCursorMoved.bind(this), 200); - events_2.default.on('CursorMoved', this.onCursorMoved.bind(this, false), null, this.disposables); - events_2.default.on('CursorMovedI', this.onCursorMoved.bind(this, true), null, this.disposables); - this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - this.onCursorMoved.clear(); - this.cancel(); - })); - } - _onCursorMoved(insertMode, bufnr, cursor) { - if (bufnr == this._bufnr) - return; - if (bufnr == this.targetBufnr && object_1.equals(cursor, this.cursor)) { - // cursor not moved - return; - } - if (this.autoHide) { - this.close(); - return; - } - if (!insertMode || bufnr != this.targetBufnr) { - this.close(); - return; - } - } - /** - * @deprecated use show method instead - */ - async create(docs, allowSelection = false, offsetX = 0) { - let { floating, textprop } = this.env; - if (!floating && !textprop) - return; - this.onCursorMoved.clear(); - if (docs.length == 0 || docs.every(doc => doc.content.length == 0)) { - this.close(); - return; - } - this.cancel(); - let release = await this.mutex.acquire(); - try { - await this.createPopup(docs, { allowSelection, offsetX }); - release(); - } - catch (e) { - release(); - logger.error(`Error on create popup:`, e.message); - this.close(); - } - } - async show(docs, config = {}) { - let { floating, textprop } = this.env; - if (!floating && !textprop) - return; - this.onCursorMoved.clear(); - if (docs.length == 0 || docs.every(doc => doc.content.length == 0)) { - this.close(); - return; - } - this.cancel(); - let release = await this.mutex.acquire(); - try { - await this.createPopup(docs, config); - release(); - } - catch (e) { - release(); - logger.error(`Error on create popup:`, e.message); - this.close(); - } - } - async createPopup(docs, opts) { - let tokenSource = this.tokenSource = new vscode_languageserver_protocol_1.CancellationTokenSource(); - let token = tokenSource.token; - let { nvim, floatBuffer } = this; - let lines = floatBuffer_1.default.getLines(docs, !this.env.isVim); - let floatConfig = { - allowSelection: opts.allowSelection || false, - pumAlignTop: this.pumAlignTop, - preferTop: typeof opts.preferTop === 'boolean' ? opts.preferTop : this.preferTop, - maxWidth: this.maxWidth || 80, - maxHeight: this.maxHeight, - offsetX: opts.offsetX || 0, - title: opts.title || '' - }; - if (opts.border) { - floatConfig.border = opts.border; - } - if (opts.title && !floatConfig.border) { - floatConfig.border = [1, 1, 1, 1]; - } - let arr = await this.nvim.call('coc#float#get_float_mode', [lines, floatConfig]); - if (!arr || token.isCancellationRequested) - return; - let [mode, targetBufnr, cursor, config] = arr; - config.relative = 'cursor'; - config.title = floatConfig.title; - config.border = floatConfig.border; - config.close = opts.close ? 1 : 0; - if (opts.cursorline) - config.cursorline = 1; - if (this.autoHide) - config.autohide = 1; - this.targetBufnr = targetBufnr; - this.cursor = cursor; - // calculat highlights - await floatBuffer.setDocuments(docs, config.width); - if (token.isCancellationRequested) - return; - if (mode == 's') - nvim.call('feedkeys', ['\x1b', "in"], true); - // create window - let res = await this.nvim.call('coc#float#create_float_win', [this.winid, this._bufnr, config]); - if (!res) - return; - this.onCursorMoved.clear(); - let winid = this.winid = res[0]; - let bufnr = this._bufnr = res[1]; - if (token.isCancellationRequested) - return; - nvim.pauseNotification(); - if (!this.env.isVim) { - nvim.call('coc#util#win_gotoid', [winid], true); - this.floatBuffer.setLines(bufnr); - nvim.command(`noa normal! gg0`, true); - nvim.call('coc#float#nvim_scrollbar', [winid], true); - nvim.command('noa wincmd p', true); - } - else { - // no need to change cursor position - this.floatBuffer.setLines(bufnr, winid); - nvim.call('win_execute', [winid, `noa normal! gg0`], true); - nvim.command('redraw', true); - } - this.emit('show', winid, bufnr); - let result = await nvim.resumeNotification(); - if (Array.isArray(result[1]) && result[1][0] == 0) { - // invalid window - this.winid = null; - } - if (mode == 's' && !token.isCancellationRequested) { - nvim.call('CocActionAsync', ['selectCurrentPlaceholder'], true); - await util_1.wait(50); - } - this.onCursorMoved.clear(); - } - /** - * Close float window - */ - close() { - let { winid, nvim } = this; - this.cancel(); - if (winid) { - // TODO: sometimes this won't work at all - nvim.pauseNotification(); - this.winid = 0; - nvim.call('coc#float#close', [winid], true); - if (this.env.isVim) - this.nvim.command('redraw', true); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true); - } - } - cancel() { - let { tokenSource } = this; - if (tokenSource) { - tokenSource.cancel(); - this.tokenSource = null; - } - } - dispose() { - this.removeAllListeners(); - util_1.disposeAll(this.disposables); - } - get bufnr() { - return this._bufnr; - } - get buffer() { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : null; - } - get window() { - return this.winid ? this.nvim.createWindow(this.winid) : null; - } - async activated() { - if (!this.winid) - return false; - return await this.nvim.call('coc#float#valid', [this.winid]) != 0; - } -} -exports.default = FloatFactory; -//# sourceMappingURL=floatFactory.js.map - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Mutex = void 0; -class Mutex { - constructor() { - this.tasks = []; - this.count = 1; - } - sched() { - if (this.count > 0 && this.tasks.length > 0) { - this.count--; - let next = this.tasks.shift(); - next(); - } - } - get busy() { - return this.count == 0; - } - acquire() { - return new Promise(res => { - let task = () => { - let released = false; - res(() => { - if (!released) { - released = true; - this.count++; - this.sched(); - } - }); - }; - this.tasks.push(task); - process.nextTick(this.sched.bind(this)); - }); - } - use(f) { - return this.acquire() - .then(release => f() - .then(res => { - release(); - return res; - }) - .catch(err => { - release(); - throw err; - })); - } -} -exports.Mutex = Mutex; -//# sourceMappingURL=mutex.js.map - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const array_1 = __webpack_require__(257); -const highlight_1 = __webpack_require__(258); -const string_1 = __webpack_require__(314); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const logger = __webpack_require__(64)('model-floatBuffer'); -class FloatBuffer { - constructor(nvim) { - this.nvim = nvim; - this.lines = []; - this.positions = []; - this.enableHighlight = true; - this.highlightTimeout = 500; - let config = workspace_1.default.getConfiguration('coc.preferences'); - this.enableHighlight = config.get('enableFloatHighlight', true); - this.highlightTimeout = config.get('highlightTimeout', 500); - } - async setDocuments(docs, width) { - let fragments = this.calculateFragments(docs, width); - let { filetype } = docs[0]; - if (!highlight_1.diagnosticFiletypes.includes(filetype)) { - this.filetype = filetype; - } - if (workspace_1.default.isNvim) { - fragments = fragments.reduce((p, c) => { - p.push(...this.splitFragment(c, 'sh')); - return p; - }, []); - } - if (this.enableHighlight) { - let arr = await Promise.all(fragments.map(f => highlight_1.getHiglights(f.lines, f.filetype, this.highlightTimeout).then(highlights => highlights.map(highlight => Object.assign({}, highlight, { line: highlight.line + f.start }))))); - this.highlights = arr.reduce((p, c) => p.concat(c), []); - } - else { - this.highlights = []; - } - } - splitFragment(fragment, defaultFileType) { - let res = []; - let filetype = fragment.filetype; - let lines = []; - let curr = fragment.start; - let inBlock = false; - for (let line of fragment.lines) { - let ms = line.match(/^\s*```\s*(\w+)?/); - if (ms != null) { - if (lines.length) { - res.push({ lines, filetype: fixFiletype(filetype), start: curr - lines.length }); - lines = []; - } - inBlock = !inBlock; - filetype = inBlock ? ms[1] || defaultFileType : fragment.filetype; - } - else { - lines.push(line); - curr = curr + 1; - } - } - if (lines.length) { - res.push({ lines, filetype: fixFiletype(filetype), start: curr - lines.length }); - lines = []; - } - return res; - } - setLines(bufnr, winid) { - let { lines, nvim, highlights } = this; - let buffer = nvim.createBuffer(bufnr); - nvim.call('clearmatches', winid ? [winid] : [], true); - // vim will clear text properties - if (workspace_1.default.isNvim) - buffer.clearNamespace(-1, 0, -1); - if (workspace_1.default.isNvim) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }, true); - } - else { - nvim.call('coc#util#set_buf_lines', [bufnr, lines], true); - } - if (highlights && highlights.length) { - let positions = []; - for (let highlight of highlights) { - if (highlight.hlGroup == 'htmlBold') { - highlight.hlGroup = 'CocBold'; - } - buffer.addHighlight(Object.assign({ srcId: workspace_1.default.createNameSpace('coc-float') }, highlight)).logError(); - if (highlight.isMarkdown) { - let line = lines[highlight.line]; - if (line) { - let si = string_1.characterIndex(line, highlight.colStart); - let ei = string_1.characterIndex(line, highlight.colEnd) - 1; - let before = line[si]; - let after = line[ei]; - if (before == after && ['_', '`', '*'].includes(before)) { - if (before == '_' && line[si + 1] == '_' && line[ei - 1] == '_' && si + 1 < ei - 1) { - positions.push([highlight.line + 1, highlight.colStart + 1, 2]); - positions.push([highlight.line + 1, highlight.colEnd - 1, 2]); - } - else { - positions.push([highlight.line + 1, highlight.colStart + 1]); - positions.push([highlight.line + 1, highlight.colEnd]); - } - } - if (highlight.colEnd - highlight.colStart == 2 && before == '\\') { - positions.push([highlight.line + 1, highlight.colStart + 1]); - } - } - } - } - for (let arr of array_1.group(positions, 8)) { - if (winid) { - nvim.call('win_execute', [winid, `call matchaddpos('Conceal', ${JSON.stringify(arr)},11)`], true); - } - else { - nvim.call('matchaddpos', ['Conceal', arr, 11], true); - } - } - } - for (let arr of array_1.group(this.positions || [], 8)) { - arr = arr.filter(o => o[2] != 0); - if (arr.length) { - if (winid) { - nvim.call('win_execute', [winid, `call matchaddpos('CocUnderline', ${JSON.stringify(arr)},12)`], true); - } - else { - nvim.call('matchaddpos', ['CocUnderline', arr, 12], true); - } - } - } - if (winid && this.enableHighlight && this.filetype) { - nvim.call('win_execute', [winid, `runtime! syntax/${this.filetype}.vim`], true); - } - } - calculateFragments(docs, width) { - let fragments = []; - let idx = 0; - let currLine = 0; - let newLines = []; - let positions = this.positions = []; - for (let doc of docs) { - let lines = []; - let arr = doc.content.split(/\r?\n/); - for (let str of arr) { - if (doc.filetype == 'markdown') { - // replace `\` surrounded by `__` because bug of markdown highlight in vim. - str = str.replace(/__(.+?)__/g, (_, p1) => { - return `__${p1.replace(/\\_/g, '_').replace(/\\\\/g, '\\')}__`; - }); - } - lines.push(str); - if (doc.active) { - let part = str.slice(doc.active[0], doc.active[1]); - positions.push([currLine + 1, doc.active[0] + 1, string_1.byteLength(part)]); - } - } - fragments.push({ - start: currLine, - lines, - filetype: doc.filetype - }); - let filtered = workspace_1.default.isNvim && doc.filetype === 'markdown' ? lines.filter(s => !/^\s*```/.test(s)) : lines; - newLines.push(...filtered); - if (idx != docs.length - 1) { - newLines.push('—'.repeat(width)); - currLine = newLines.length; - } - idx = idx + 1; - } - this.lines = newLines; - return fragments; - } - // return lines for calculate dimension - // TODO need use parsed lines for markdown - static getLines(docs, isNvim) { - let res = []; - for (let i = 0; i < docs.length; i++) { - let doc = docs[i]; - let lines = doc.content.split(/\r?\n/); - for (let line of lines) { - if (isNvim && doc.filetype == 'markdown' && /^\s*```/.test(line)) { - continue; - } - res.push(line); - } - if (i != docs.length - 1) { - res.push('-'); - } - } - return res; - } - static getDimension(docs, maxWidth, maxHeight) { - // width contains padding - if (maxWidth <= 2 || maxHeight <= 0) - return { width: 0, height: 0 }; - let arr = []; - for (let doc of docs) { - let lines = doc.content.split(/\r?\n/); - for (let line of lines) { - if (workspace_1.default.isNvim && doc.filetype == 'markdown' && /^\s*```/.test(line)) { - continue; - } - arr.push(string_1.byteLength(line.replace(/\t/g, ' ')) + 2); - } - } - let width = Math.min(Math.max(...arr), maxWidth); - if (width <= 2) - return { width: 0, height: 0 }; - let height = docs.length - 1; - for (let w of arr) { - height = height + Math.max(Math.ceil((w - 2) / (width - 2)), 1); - } - return { width, height: Math.min(height, maxHeight) }; - } -} -exports.default = FloatBuffer; -function fixFiletype(filetype) { - if (filetype == 'ts') - return 'typescript'; - if (filetype == 'js') - return 'javascript'; - if (filetype == 'bash') - return 'sh'; - return filetype; -} -//# sourceMappingURL=floatBuffer.js.map - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.flatMap = exports.lastIndex = exports.distinct = exports.group = exports.tail = exports.splitArray = exports.intersect = void 0; -function intersect(array, other) { - for (let item of other) { - if (array.includes(item)) { - return true; - } - } - return false; -} -exports.intersect = intersect; -function splitArray(array, fn) { - let res = [[], []]; - for (let item of array) { - if (fn(item)) { - res[0].push(item); - } - else { - res[1].push(item); - } - } - return res; -} -exports.splitArray = splitArray; -function tail(array, n = 0) { - return array[array.length - (1 + n)]; -} -exports.tail = tail; -function group(array, size) { - let len = array.length; - let res = []; - for (let i = 0; i < Math.ceil(len / size); i++) { - res.push(array.slice(i * size, (i + 1) * size)); - } - return res; -} -exports.group = group; -/** - * Removes duplicates from the given array. The optional keyFn allows to specify - * how elements are checked for equalness by returning a unique string for each. - */ -function distinct(array, keyFn) { - if (!keyFn) { - return array.filter((element, position) => array.indexOf(element) === position); - } - const seen = Object.create(null); - return array.filter(elem => { - const key = keyFn(elem); - if (seen[key]) { - return false; - } - seen[key] = true; - return true; - }); -} -exports.distinct = distinct; -function lastIndex(array, fn) { - let i = array.length - 1; - while (i >= 0) { - if (fn(array[i])) { - break; - } - i--; - } - return i; -} -exports.lastIndex = lastIndex; -exports.flatMap = (xs, f) => xs.reduce((x, y) => [...x, ...f(y)], []); -//# sourceMappingURL=array.js.map - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getHiglights = exports.diagnosticFiletypes = void 0; -const tslib_1 = __webpack_require__(65); -const neovim_1 = __webpack_require__(155); -const cp = tslib_1.__importStar(__webpack_require__(239)); -const crypto_1 = __webpack_require__(221); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const uuid_1 = __webpack_require__(259); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const lodash_1 = __webpack_require__(332); -const processes_1 = __webpack_require__(333); -const string_1 = __webpack_require__(314); -const logger = __webpack_require__(64)('util-highlights'); -exports.diagnosticFiletypes = ['Error', 'Warning', 'Info', 'Hint']; -const cache = {}; -let env = null; -// get highlights by send text to another neovim instance. -function getHiglights(lines, filetype, timeout = 500) { - const hlMap = new Map(); - const content = lines.join('\n'); - if (exports.diagnosticFiletypes.includes(filetype)) { - let highlights = lines.map((line, i) => ({ - line: i, - colStart: 0, - colEnd: string_1.byteLength(line), - hlGroup: `Coc${filetype}Float` - })); - return Promise.resolve(highlights); - } - if (filetype == 'javascriptreact') { - filetype = 'javascript'; - } - if (filetype == 'typescriptreact') { - filetype = 'typescript'; - } - let maxBytes = lines.reduce((p, c) => Math.max(p, string_1.byteLength(c)), 0); - const id = crypto_1.createHash('md5').update(content).digest('hex'); - if (cache[id]) - return Promise.resolve(cache[id]); - if (workspace_1.default.env.isVim) - return Promise.resolve([]); - const res = []; - let nvim; - return new Promise(async (resolve) => { - if (!env) { - env = await workspace_1.default.nvim.call('coc#util#highlight_options'); - if (!env) - resolve([]); - let paths = env.runtimepath.split(','); - let dirs = paths.filter(p => { - if (env.colorscheme) { - let schemeFile = path_1.default.join(p, `colors/${env.colorscheme}.vim`); - if (fs_1.default.existsSync(schemeFile)) - return true; - } - if (fs_1.default.existsSync(path_1.default.join(p, 'syntax'))) - return true; - if (fs_1.default.existsSync(path_1.default.join(p, 'after/syntax'))) - return true; - return false; - }); - env.runtimepath = dirs.join(','); - } - let prog = workspace_1.default.env.progpath || 'nvim'; - let proc = cp.spawn(prog, ['-u', 'NORC', '-i', 'NONE', '--embed', '--noplugin', uuid_1.v4()], { - shell: false, - cwd: os_1.default.tmpdir(), - env: lodash_1.omit(process.env, ['NVIM_LISTEN_ADDRESS', 'VIM_NODE_RPC']) - }); - proc.on('error', error => { - logger.info('highlight error:', error); - resolve([]); - }); - let timer; - let exited = false; - const exit = () => { - if (exited) - return; - exited = true; - if (timer) - clearTimeout(timer); - if (nvim) { - nvim.command('qa!').catch(() => { - let killed = processes_1.terminate(proc); - if (!killed) { - setTimeout(() => { - processes_1.terminate(proc); - }, 50); - } - }); - } - }; - try { - proc.once('exit', () => { - if (exited) - return; - logger.info('highlight nvim exited.'); - resolve([]); - }); - timer = setTimeout(() => { - exit(); - resolve([]); - }, timeout); - nvim = neovim_1.attach({ proc }, null, false); - const callback = (method, args) => { - if (method == 'redraw') { - for (let arr of args) { - let [name, ...list] = arr; - if (name == 'hl_attr_define') { - for (let item of list) { - let id = item[0]; - let { hi_name } = item[item.length - 1][0]; - hlMap.set(id, hi_name); - } - } - if (name == 'grid_line') { - // logger.debug('list:', JSON.stringify(list, null, 2)) - for (let def of list) { - let [, line, col, cells] = def; - if (line >= lines.length) - continue; - let colStart = 0; - let hlGroup = ''; - let currId = 0; - for (let i = 0; i < cells.length; i++) { - let cell = cells[i]; - let [ch, hlId, repeat] = cell; - repeat = repeat || 1; - let len = string_1.byteLength(ch.repeat(repeat)); - // append result - if (hlId == 0 || (hlId > 0 && hlId != currId)) { - if (hlGroup) { - res.push({ - line, - hlGroup, - colStart, - colEnd: col, - isMarkdown: filetype == 'markdown' - }); - } - colStart = col; - hlGroup = hlId == 0 ? '' : hlMap.get(hlId); - } - if (hlId != null) - currId = hlId; - col = col + len; - } - if (hlGroup) { - res.push({ - hlGroup, - line, - colStart, - colEnd: col, - isMarkdown: filetype == 'markdown' - }); - } - } - cache[id] = res; - exit(); - resolve(res); - } - } - } - }; - nvim.on('notification', callback); - await nvim.callAtomic([ - ['nvim_set_option', ['runtimepath', env.runtimepath]], - ['nvim_command', [`highlight! link Normal CocFloating`]], - ['nvim_command', ['syntax enable']], - ['nvim_command', [`colorscheme ${env.colorscheme || 'default'}`]], - ['nvim_command', [`set background=${env.background}`]], - ['nvim_command', ['set nowrap']], - ['nvim_command', ['set noswapfile']], - ['nvim_command', ['set nobackup']], - ['nvim_command', ['set noshowmode']], - ['nvim_command', ['set noruler']], - ['nvim_command', ['set undolevels=-1']], - ['nvim_command', ['set laststatus=0']], - ...lines.map((line, idx) => ['nvim_call_function', ['setline', [idx + 1, line]]]), - ['nvim_command', [`runtime! syntax/${filetype}.vim`]] - ]); - await nvim.uiAttach(maxBytes + 10, lines.length + 1, { - ext_hlstate: true, - ext_linegrid: true - }); - } - catch (e) { - logger.error(e); - exit(); - resolve([]); - } - }); -} -exports.getHiglights = getHiglights; -//# sourceMappingURL=highlight.js.map - -/***/ }), -/* 259 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v1_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(260); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v1", function() { return _v1_js__WEBPACK_IMPORTED_MODULE_0__["default"]; }); - -/* harmony import */ var _v3_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(263); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v3", function() { return _v3_js__WEBPACK_IMPORTED_MODULE_1__["default"]; }); - -/* harmony import */ var _v4_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(266); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v4", function() { return _v4_js__WEBPACK_IMPORTED_MODULE_2__["default"]; }); - -/* harmony import */ var _v5_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(267); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v5", function() { return _v5_js__WEBPACK_IMPORTED_MODULE_3__["default"]; }); - - - - - - -/***/ }), -/* 260 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(261); -/* harmony import */ var _bytesToUuid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(262); - - // **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -var _nodeId; - -var _clockseq; // Previous uuid creation time - - -var _lastMSecs = 0; -var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_0__["default"])(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf ? buf : Object(_bytesToUuid_js__WEBPACK_IMPORTED_MODULE_1__["default"])(b); -} - -/* harmony default export */ __webpack_exports__["default"] = (v1); - -/***/ }), -/* 261 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return rng; }); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(221); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__); - -function rng() { - return crypto__WEBPACK_IMPORTED_MODULE_0___default.a.randomBytes(16); -} - -/***/ }), -/* 262 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; - -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - - return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(''); -} - -/* harmony default export */ __webpack_exports__["default"] = (bytesToUuid); - -/***/ }), -/* 263 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(264); -/* harmony import */ var _md5_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(265); - - -const v3 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v3', 0x30, _md5_js__WEBPACK_IMPORTED_MODULE_1__["default"]); -/* harmony default export */ __webpack_exports__["default"] = (v3); - -/***/ }), -/* 264 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DNS", function() { return DNS; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URL", function() { return URL; }); -/* harmony import */ var _bytesToUuid_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(262); - - -function uuidToBytes(uuid) { - // Note: We assume we're being passed a valid uuid string - var bytes = []; - uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) { - bytes.push(parseInt(hex, 16)); - }); - return bytes; -} - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - var bytes = new Array(str.length); - - for (var i = 0; i < str.length; i++) { - bytes[i] = str.charCodeAt(i); - } - - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -/* harmony default export */ __webpack_exports__["default"] = (function (name, version, hashfunc) { - var generateUUID = function (value, namespace, buf, offset) { - var off = buf && offset || 0; - if (typeof value == 'string') value = stringToBytes(value); - if (typeof namespace == 'string') namespace = uuidToBytes(namespace); - if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); - if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3 - - var bytes = hashfunc(namespace.concat(value)); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - for (var idx = 0; idx < 16; ++idx) { - buf[off + idx] = bytes[idx]; - } - } - - return buf || Object(_bytesToUuid_js__WEBPACK_IMPORTED_MODULE_0__["default"])(bytes); - }; // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -}); - -/***/ }), -/* 265 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(221); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__); - - -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return crypto__WEBPACK_IMPORTED_MODULE_0___default.a.createHash('md5').update(bytes).digest(); -} - -/* harmony default export */ __webpack_exports__["default"] = (md5); - -/***/ }), -/* 266 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(261); -/* harmony import */ var _bytesToUuid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(262); - - - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof options == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - - options = options || {}; - var rnds = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_0__["default"])(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || Object(_bytesToUuid_js__WEBPACK_IMPORTED_MODULE_1__["default"])(rnds); -} - -/* harmony default export */ __webpack_exports__["default"] = (v4); - -/***/ }), -/* 267 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(264); -/* harmony import */ var _sha1_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(268); - - -const v5 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v5', 0x50, _sha1_js__WEBPACK_IMPORTED_MODULE_1__["default"]); -/* harmony default export */ __webpack_exports__["default"] = (v5); - -/***/ }), -/* 268 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(221); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__); - - -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return crypto__WEBPACK_IMPORTED_MODULE_0___default.a.createHash('sha1').update(bytes).digest(); -} - -/* harmony default export */ __webpack_exports__["default"] = (sha1); - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Workspace = void 0; -const tslib_1 = __webpack_require__(65); -const bytes_1 = tslib_1.__importDefault(__webpack_require__(270)); -const fast_diff_1 = tslib_1.__importDefault(__webpack_require__(271)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const rimraf_1 = tslib_1.__importDefault(__webpack_require__(279)); -const util_1 = tslib_1.__importDefault(__webpack_require__(74)); -const semver_1 = tslib_1.__importDefault(__webpack_require__(1)); -const uuid_1 = __webpack_require__(259); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_languageserver_textdocument_1 = __webpack_require__(295); -const vscode_uri_1 = __webpack_require__(243); -const which_1 = tslib_1.__importDefault(__webpack_require__(244)); -const configuration_1 = tslib_1.__importDefault(__webpack_require__(296)); -const shape_1 = tslib_1.__importDefault(__webpack_require__(307)); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const channels_1 = tslib_1.__importDefault(__webpack_require__(308)); -const db_1 = tslib_1.__importDefault(__webpack_require__(311)); -const document_1 = tslib_1.__importDefault(__webpack_require__(312)); -const menu_1 = tslib_1.__importDefault(__webpack_require__(317)); -const fileSystemWatcher_1 = tslib_1.__importDefault(__webpack_require__(318)); -const mru_1 = tslib_1.__importDefault(__webpack_require__(319)); -const resolver_1 = tslib_1.__importDefault(__webpack_require__(320)); -const status_1 = tslib_1.__importDefault(__webpack_require__(322)); -const task_1 = tslib_1.__importDefault(__webpack_require__(323)); -const terminal_1 = tslib_1.__importDefault(__webpack_require__(324)); -const willSaveHandler_1 = tslib_1.__importDefault(__webpack_require__(325)); -const types_1 = __webpack_require__(297); -const array_1 = __webpack_require__(257); -const fs_2 = __webpack_require__(306); -const index_1 = __webpack_require__(238); -const match_1 = __webpack_require__(326); -const mutex_1 = __webpack_require__(255); -const position_1 = __webpack_require__(315); -const string_1 = __webpack_require__(314); -const watchman_1 = tslib_1.__importDefault(__webpack_require__(327)); -const object_1 = __webpack_require__(249); -const logger = __webpack_require__(64)('workspace'); -let NAME_SPACE = 1080; -class Workspace { - constructor() { - this.keymaps = new Map(); - this.mutex = new mutex_1.Mutex(); - this.resolver = new resolver_1.default(); - this.rootPatterns = new Map(); - this._workspaceFolders = []; - this._insertMode = false; - this._cwd = process.cwd(); - this._initialized = false; - this._attached = false; - this.buffers = new Map(); - this.autocmdMaxId = 0; - this.autocmds = new Map(); - this.terminals = new Map(); - this.creatingSources = new Map(); - this.schemeProviderMap = new Map(); - this.namespaceMap = new Map(); - this.disposables = []; - this.watchedOptions = new Set(); - this._dynAutocmd = false; - this._disposed = false; - this._onDidOpenDocument = new vscode_languageserver_protocol_1.Emitter(); - this._onDidCloseDocument = new vscode_languageserver_protocol_1.Emitter(); - this._onDidChangeDocument = new vscode_languageserver_protocol_1.Emitter(); - this._onWillSaveDocument = new vscode_languageserver_protocol_1.Emitter(); - this._onDidSaveDocument = new vscode_languageserver_protocol_1.Emitter(); - this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter(); - this._onDidChangeConfiguration = new vscode_languageserver_protocol_1.Emitter(); - this._onDidWorkspaceInitialized = new vscode_languageserver_protocol_1.Emitter(); - this._onDidOpenTerminal = new vscode_languageserver_protocol_1.Emitter(); - this._onDidCloseTerminal = new vscode_languageserver_protocol_1.Emitter(); - this._onDidRuntimePathChange = new vscode_languageserver_protocol_1.Emitter(); - this.onDidCloseTerminal = this._onDidCloseTerminal.event; - this.onDidOpenTerminal = this._onDidOpenTerminal.event; - this.onDidChangeWorkspaceFolders = this._onDidChangeWorkspaceFolders.event; - this.onDidOpenTextDocument = this._onDidOpenDocument.event; - this.onDidCloseTextDocument = this._onDidCloseDocument.event; - this.onDidChangeTextDocument = this._onDidChangeDocument.event; - this.onWillSaveTextDocument = this._onWillSaveDocument.event; - this.onDidSaveTextDocument = this._onDidSaveDocument.event; - this.onDidChangeConfiguration = this._onDidChangeConfiguration.event; - this.onDidWorkspaceInitialized = this._onDidWorkspaceInitialized.event; - this.onDidRuntimePathChange = this._onDidRuntimePathChange.event; - let json = __webpack_require__(331); - this.version = json.version; - this.configurations = this.createConfigurations(); - this.willSaveUntilHandler = new willSaveHandler_1.default(this); - let cwd = process.cwd(); - if (cwd != os_1.default.homedir() && fs_2.inDirectory(cwd, ['.vim'])) { - this._workspaceFolders.push({ - uri: vscode_uri_1.URI.file(cwd).toString(), - name: path_1.default.basename(cwd) - }); - } - this.setMessageLevel(); - } - async init() { - let { nvim } = this; - this.statusLine = new status_1.default(nvim); - this._env = await nvim.call('coc#util#vim_info'); - this._insertMode = this._env.mode.startsWith('insert'); - let preferences = this.getConfiguration('coc.preferences'); - let maxFileSize = preferences.get('maxFileSize', '10MB'); - this.maxFileSize = bytes_1.default.parse(maxFileSize); - this.menu = new menu_1.default(nvim, this._env); - if (this._env.workspaceFolders) { - this._workspaceFolders = this._env.workspaceFolders.map(f => ({ - uri: vscode_uri_1.URI.file(f).toString(), - name: path_1.default.dirname(f) - })); - } - this.configurations.updateUserConfig(this._env.config); - events_1.default.on('InsertEnter', () => { - this._insertMode = true; - }, null, this.disposables); - events_1.default.on('InsertLeave', () => { - this._insertMode = false; - }, null, this.disposables); - events_1.default.on('BufWinLeave', (_, winid) => { - this.nvim.call('coc#util#clear_pos_matches', ['^Coc', winid], true); - }, null, this.disposables); - events_1.default.on('BufEnter', this.onBufEnter, this, this.disposables); - events_1.default.on('CursorMoved', this.checkCurrentBuffer, this, this.disposables); - events_1.default.on('CursorMovedI', this.checkCurrentBuffer, this, this.disposables); - events_1.default.on('DirChanged', this.onDirChanged, this, this.disposables); - events_1.default.on('BufCreate', this.onBufCreate, this, this.disposables); - events_1.default.on('BufUnload', this.onBufUnload, this, this.disposables); - events_1.default.on('TermOpen', this.onBufCreate, this, this.disposables); - events_1.default.on('TermClose', this.onBufUnload, this, this.disposables); - events_1.default.on('BufWritePost', this.onBufWritePost, this, this.disposables); - events_1.default.on('BufWritePre', this.onBufWritePre, this, this.disposables); - events_1.default.on('FileType', this.onFileTypeChange, this, this.disposables); - events_1.default.on('CursorHold', this.checkCurrentBuffer, this, this.disposables); - events_1.default.on('TextChanged', this.checkBuffer, this, this.disposables); - events_1.default.on('BufReadCmd', this.onBufReadCmd, this, this.disposables); - events_1.default.on('VimResized', (columns, lines) => { - Object.assign(this._env, { columns, lines }); - }, null, this.disposables); - await this.attach(); - this.attachChangedEvents(); - this.configurations.onDidChange(e => { - this._onDidChangeConfiguration.fire(e); - }, null, this.disposables); - this.watchOption('runtimepath', (oldValue, newValue) => { - let result = fast_diff_1.default(oldValue, newValue); - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, '').split(','); - this._onDidRuntimePathChange.fire(paths); - } - } - this._env.runtimepath = newValue; - }, this.disposables); - this.watchOption('iskeyword', (_, newValue) => { - let doc = this.getDocument(this.bufnr); - if (doc) - doc.setIskeyword(newValue); - }, this.disposables); - this.watchOption('completeopt', async (_, newValue) => { - this.env.completeOpt = newValue; - if (!this._attached) - return; - if (this.insertMode) { - let suggest = this.getConfiguration('suggest'); - if (suggest.get('autoTrigger') == 'always') { - let content = await this.nvim.call('execute', ['verbose set completeopt']); - let lines = content.split(/\r?\n/); - console.error(`Some plugin change completeopt on insert mode: ${lines[lines.length - 1].trim()}!`); - } - } - }, this.disposables); - this.watchGlobal('coc_sources_disable_map', async (_, newValue) => { - this.env.disabledSources = newValue; - }); - let provider = { - onDidChange: null, - provideTextDocumentContent: async (uri) => { - let channel = channels_1.default.get(uri.path.slice(1)); - if (!channel) - return ''; - nvim.pauseNotification(); - nvim.command('setlocal nospell nofoldenable nowrap noswapfile', true); - nvim.command('setlocal buftype=nofile bufhidden=hide', true); - nvim.command('setfiletype log', true); - await nvim.resumeNotification(); - return channel.content; - } - }; - this.disposables.push(this.registerTextDocumentContentProvider('output', provider)); - } - getConfigFile(target) { - return this.configurations.getConfigFile(target); - } - /** - * Register autocmd on vim. - */ - registerAutocmd(autocmd) { - this.autocmdMaxId += 1; - let id = this.autocmdMaxId; - this.autocmds.set(id, autocmd); - this.setupDynamicAutocmd(); - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.autocmds.delete(id); - this.setupDynamicAutocmd(); - }); - } - /** - * Watch for option change. - */ - watchOption(key, callback, disposables) { - let watching = this.watchedOptions.has(key); - if (!watching) { - this.watchedOptions.add(key); - this.setupDynamicAutocmd(); - } - let disposable = events_1.default.on('OptionSet', async (changed, oldValue, newValue) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)); - } - }); - if (disposables) { - disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - disposable.dispose(); - if (watching) - return; - this.watchedOptions.delete(key); - this.setupDynamicAutocmd(); - })); - } - } - /** - * Watch global variable, works on neovim only. - */ - watchGlobal(key, callback, disposables) { - let { nvim } = this; - nvim.call('coc#_watch', key, true); - let disposable = events_1.default.on('GlobalChange', async (changed, oldValue, newValue) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)); - } - }); - if (disposables) { - disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => { - disposable.dispose(); - nvim.call('coc#_unwatch', key, true); - })); - } - } - get cwd() { - return this._cwd; - } - get env() { - return this._env; - } - get root() { - return this._root || this.cwd; - } - get rootPath() { - return this.root; - } - get workspaceFolders() { - return this._workspaceFolders; - } - /** - * uri of current file, could be null - */ - get uri() { - let { bufnr } = this; - if (bufnr) { - let document = this.getDocument(bufnr); - if (document && document.schema == 'file') { - return document.uri; - } - } - return null; - } - get workspaceFolder() { - let { rootPath } = this; - if (rootPath == os_1.default.homedir()) - return null; - return { - uri: vscode_uri_1.URI.file(rootPath).toString(), - name: path_1.default.basename(rootPath) - }; - } - async openLocalConfig() { - let { root } = this; - if (root == os_1.default.homedir()) { - this.showMessage(`Can't create local config in home directory`, 'warning'); - return; - } - let dir = path_1.default.join(root, '.vim'); - if (!fs_1.default.existsSync(dir)) { - let res = await this.showPrompt(`Would you like to create folder'${root}/.vim'?`); - if (!res) - return; - fs_1.default.mkdirSync(dir); - } - await this.jumpTo(vscode_uri_1.URI.file(path_1.default.join(dir, index_1.CONFIG_FILE_NAME)).toString()); - } - get textDocuments() { - let docs = []; - for (let b of this.buffers.values()) { - docs.push(b.textDocument); - } - return docs; - } - get documents() { - return Array.from(this.buffers.values()); - } - createNameSpace(name = '') { - if (this.namespaceMap.has(name)) - return this.namespaceMap.get(name); - NAME_SPACE = NAME_SPACE + 1; - this.namespaceMap.set(name, NAME_SPACE); - return NAME_SPACE; - } - get channelNames() { - return channels_1.default.names; - } - get pluginRoot() { - return path_1.default.dirname(__dirname); - } - get isVim() { - return this._env.isVim; - } - get isNvim() { - return !this._env.isVim; - } - get completeOpt() { - return this._env.completeOpt; - } - get initialized() { - return this._initialized; - } - get ready() { - if (this._initialized) - return Promise.resolve(); - return new Promise(resolve => { - let disposable = this.onDidWorkspaceInitialized(() => { - disposable.dispose(); - resolve(); - }); - }); - } - /** - * Current filetypes. - */ - get filetypes() { - let res = new Set(); - for (let doc of this.documents) { - res.add(doc.filetype); - } - return res; - } - /** - * Check if selector match document. - */ - match(selector, document) { - return match_1.score(selector, document.uri, document.languageId); - } - /** - * Findup for filename or filenames from current filepath or root. - */ - async findUp(filename) { - let { cwd } = this; - let filepath = await this.nvim.call('expand', '%:p'); - filepath = path_1.default.normalize(filepath); - let isFile = filepath && path_1.default.isAbsolute(filepath); - if (isFile && !fs_2.isParentFolder(cwd, filepath, true)) { - // can't use cwd - return fs_2.findUp(filename, path_1.default.dirname(filepath)); - } - let res = fs_2.findUp(filename, cwd); - if (res && res != os_1.default.homedir()) - return res; - if (isFile) - return fs_2.findUp(filename, path_1.default.dirname(filepath)); - return null; - } - // eslint-disable-next-line @typescript-eslint/require-await - async resolveRootFolder(uri, patterns) { - let { cwd } = this; - if (uri.scheme != 'file') - return cwd; - let filepath = path_1.default.normalize(uri.fsPath); - let dir = path_1.default.dirname(filepath); - return fs_2.resolveRoot(dir, patterns) || dir; - } - /** - * Create a FileSystemWatcher instance, - * doesn't fail when watchman not found. - */ - createFileSystemWatcher(globPattern, ignoreCreate, ignoreChange, ignoreDelete) { - let watchmanPath = global.hasOwnProperty('__TEST__') ? null : this.getWatchmanPath(); - let channel = watchmanPath ? this.createOutputChannel('watchman') : null; - let promise = watchmanPath ? watchman_1.default.createClient(watchmanPath, this.root, channel) : Promise.resolve(null); - let watcher = new fileSystemWatcher_1.default(promise, globPattern, !!ignoreCreate, !!ignoreChange, !!ignoreDelete); - return watcher; - } - getWatchmanPath() { - const preferences = this.getConfiguration('coc.preferences'); - let watchmanPath = preferences.get('watchmanPath', 'watchman'); - try { - return which_1.default.sync(watchmanPath); - } - catch (e) { - return null; - } - } - /** - * Get configuration by section and optional resource uri. - */ - getConfiguration(section, resource) { - return this.configurations.getConfiguration(section, resource); - } - /** - * Get created document by uri or bufnr. - */ - getDocument(uri) { - if (typeof uri === 'number') { - return this.buffers.get(uri); - } - const caseInsensitive = index_1.platform.isWindows || index_1.platform.isMacintosh; - uri = vscode_uri_1.URI.parse(uri).toString(); - for (let doc of this.buffers.values()) { - if (!doc) - continue; - if (doc.uri === uri) - return doc; - if (caseInsensitive && doc.uri.toLowerCase() === uri.toLowerCase()) - return doc; - } - return null; - } - /** - * Get current cursor offset in document. - */ - async getOffset() { - let document = await this.document; - let pos = await this.getCursorPosition(); - let doc = vscode_languageserver_textdocument_1.TextDocument.create('file:///1', '', 0, document.getDocumentContent()); - return doc.offsetAt(pos); - } - /** - * Apply WorkspaceEdit. - */ - async applyEdit(edit) { - let { nvim } = this; - let { documentChanges, changes } = edit; - let [bufnr, cursor] = await nvim.eval('[bufnr("%"),coc#util#cursor()]'); - let document = this.getDocument(bufnr); - let uri = document ? document.uri : null; - let currEdits = null; - let locations = []; - let changeCount = 0; - const preferences = this.getConfiguration('coc.preferences'); - let promptUser = !global.hasOwnProperty('__TEST__') && preferences.get('promptWorkspaceEdit', true); - let listTarget = preferences.get('listOfWorkspaceEdit', 'quickfix'); - try { - if (documentChanges && documentChanges.length) { - let changedUris = this.getChangedUris(documentChanges); - changeCount = changedUris.length; - if (promptUser) { - let diskCount = 0; - for (let uri of changedUris) { - if (!this.getDocument(uri)) { - diskCount = diskCount + 1; - } - } - if (diskCount) { - let res = await this.showPrompt(`${diskCount} documents on disk would be loaded for change, confirm?`); - if (!res) - return; - } - } - let changedMap = new Map(); - // let changes: Map = new Map() - let textEdits = []; - for (let i = 0; i < documentChanges.length; i++) { - let change = documentChanges[i]; - if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change)) { - let { textDocument, edits } = change; - let next = documentChanges[i + 1]; - textEdits.push(...edits); - if (next && vscode_languageserver_protocol_1.TextDocumentEdit.is(next) && object_1.equals((next).textDocument, textDocument)) { - continue; - } - let doc = await this.loadFile(textDocument.uri); - if (textDocument.uri == uri) - currEdits = textEdits; - await doc.applyEdits(textEdits); - for (let edit of textEdits) { - locations.push({ uri: doc.uri, range: edit.range }); - } - textEdits = []; - } - else if (vscode_languageserver_protocol_1.CreateFile.is(change)) { - let file = vscode_uri_1.URI.parse(change.uri).fsPath; - await this.createFile(file, change.options); - } - else if (vscode_languageserver_protocol_1.RenameFile.is(change)) { - changedMap.set(change.oldUri, change.newUri); - await this.renameFile(vscode_uri_1.URI.parse(change.oldUri).fsPath, vscode_uri_1.URI.parse(change.newUri).fsPath, change.options); - } - else if (vscode_languageserver_protocol_1.DeleteFile.is(change)) { - await this.deleteFile(vscode_uri_1.URI.parse(change.uri).fsPath, change.options); - } - } - // fix location uris on renameFile - if (changedMap.size) { - locations.forEach(location => { - let newUri = changedMap.get(location.uri); - if (newUri) - location.uri = newUri; - }); - } - } - else if (changes) { - let uris = Object.keys(changes); - let unloaded = uris.filter(uri => this.getDocument(uri) == null); - if (unloaded.length) { - if (promptUser) { - let res = await this.showPrompt(`${unloaded.length} documents on disk would be loaded for change, confirm?`); - if (!res) - return; - } - await this.loadFiles(unloaded); - } - for (let uri of Object.keys(changes)) { - let document = this.getDocument(uri); - if (vscode_uri_1.URI.parse(uri).toString() == uri) - currEdits = changes[uri]; - let edits = changes[uri]; - for (let edit of edits) { - locations.push({ uri: document.uri, range: edit.range }); - } - await document.applyEdits(edits); - } - changeCount = uris.length; - } - if (currEdits) { - let changed = position_1.getChangedFromEdits({ line: cursor[0], character: cursor[1] }, currEdits); - if (changed) - await this.moveTo({ - line: cursor[0] + changed.line, - character: cursor[1] + changed.character - }); - } - if (locations.length) { - let items = await Promise.all(locations.map(loc => this.getQuickfixItem(loc))); - let silent = locations.every(l => l.uri == uri); - if (listTarget == 'quickfix') { - await this.nvim.call('setqflist', [items]); - if (!silent) - this.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :copen to open quickfix list`, 'more'); - } - else if (listTarget == 'location') { - await nvim.setVar('coc_jump_locations', items); - if (!silent) - this.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :CocList location to manage changed locations`, 'more'); - } - } - } - catch (e) { - logger.error(e); - this.showMessage(`Error on applyEdits: ${e.message}`, 'error'); - return false; - } - await index_1.wait(50); - return true; - } - /** - * Convert location to quickfix item. - */ - async getQuickfixItem(loc, text, type = '', module) { - if (vscode_languageserver_protocol_1.LocationLink.is(loc)) { - loc = vscode_languageserver_protocol_1.Location.create(loc.targetUri, loc.targetRange); - } - let doc = this.getDocument(loc.uri); - let { uri, range } = loc; - let { line, character } = range.start; - let u = vscode_uri_1.URI.parse(uri); - let bufnr = doc ? doc.bufnr : -1; - if (!text && u.scheme == 'file') { - text = await this.getLine(uri, line); - character = string_1.byteIndex(text, character); - } - let item = { - uri, - filename: u.scheme == 'file' ? u.fsPath : uri, - lnum: line + 1, - col: character + 1, - text: text || '', - range - }; - if (module) - item.module = module; - if (type) - item.type = type; - if (bufnr != -1) - item.bufnr = bufnr; - return item; - } - /** - * Create persistence Mru instance. - */ - createMru(name) { - return new mru_1.default(name); - } - /** - * Get selected range for current document - */ - async getSelectedRange(mode, document) { - let { nvim } = this; - if (mode == 'n') { - let line = await nvim.call('line', ['.']); - let content = document.getline(line - 1); - if (!content.length) - return null; - return vscode_languageserver_protocol_1.Range.create(line - 1, 0, line - 1, content.length); - } - if (!['v', 'V', 'char', 'line', '\x16'].includes(mode)) { - throw new Error(`Mode '${mode}' not supported`); - } - let isVisual = ['v', 'V', '\x16'].includes(mode); - let [, sl, sc] = await nvim.call('getpos', isVisual ? `'<` : `'[`); - let [, el, ec] = await nvim.call('getpos', isVisual ? `'>` : `']`); - let range = vscode_languageserver_protocol_1.Range.create(document.getPosition(sl, sc), document.getPosition(el, ec)); - if (mode == 'v' || mode == '\x16') { - range.end.character = range.end.character + 1; - } - return range; - } - /** - * Visual select range of current document - */ - async selectRange(range) { - let { nvim } = this; - let { start, end } = range; - let [bufnr, ve, selection] = await nvim.eval(`[bufnr('%'), &virtualedit, &selection, mode()]`); - let document = this.getDocument(bufnr); - if (!document) - return; - let line = document.getline(start.line); - let col = line ? string_1.byteLength(line.slice(0, start.character)) : 0; - let endLine = document.getline(end.line); - let endCol = endLine ? string_1.byteLength(endLine.slice(0, end.character)) : 0; - let move_cmd = ''; - let resetVirtualEdit = false; - move_cmd += 'v'; - endCol = await nvim.eval(`virtcol([${end.line + 1}, ${endCol}])`); - if (selection == 'inclusive') { - if (end.character == 0) { - move_cmd += `${end.line}G`; - } - else { - move_cmd += `${end.line + 1}G${endCol}|`; - } - } - else if (selection == 'old') { - move_cmd += `${end.line + 1}G${endCol}|`; - } - else { - move_cmd += `${end.line + 1}G${endCol + 1}|`; - } - col = await nvim.eval(`virtcol([${start.line + 1}, ${col}])`); - move_cmd += `o${start.line + 1}G${col + 1}|o`; - nvim.pauseNotification(); - if (ve != 'onemore') { - resetVirtualEdit = true; - nvim.setOption('virtualedit', 'onemore', true); - } - nvim.command(`noa call cursor(${start.line + 1},${col + (move_cmd == 'a' ? 0 : 1)})`, true); - // nvim.call('eval', [`feedkeys("${move_cmd}", 'in')`], true) - nvim.command(`normal! ${move_cmd}`, true); - if (resetVirtualEdit) - nvim.setOption('virtualedit', ve, true); - if (this.isVim) - nvim.command('redraw', true); - await nvim.resumeNotification(); - } - /** - * Populate locations to UI. - */ - async showLocations(locations) { - let items = await Promise.all(locations.map(loc => this.getQuickfixItem(loc))); - let { nvim } = this; - const preferences = this.getConfiguration('coc.preferences'); - if (preferences.get('useQuickfixForLocations', false)) { - let openCommand = await nvim.getVar('coc_quickfix_open_command'); - if (typeof openCommand != 'string') { - openCommand = items.length < 10 ? `copen ${items.length}` : 'copen'; - } - nvim.pauseNotification(); - nvim.call('setqflist', [items], true); - nvim.command(openCommand, true); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true); - } - else { - await nvim.setVar('coc_jump_locations', items); - if (this.env.locationlist) { - nvim.command('CocList --normal --auto-preview location', true); - } - else { - nvim.call('coc#util#do_autocmd', ['CocLocationsChange'], true); - } - } - } - /** - * Get content of line by uri and line. - */ - async getLine(uri, line) { - let document = this.getDocument(uri); - if (document) - return document.getline(line) || ''; - if (!uri.startsWith('file:')) - return ''; - return await fs_2.readFileLine(vscode_uri_1.URI.parse(uri).fsPath, line); - } - /** - * Get position for matchaddpos from range & uri - */ - async getHighlightPositions(uri, range) { - let res = []; - if (position_1.comparePosition(range.start, range.end) == 0) - return []; - let arr = []; - for (let i = range.start.line; i <= range.end.line; i++) { - let curr = await this.getLine(uri, range.start.line); - if (!curr) - continue; - let sc = i == range.start.line ? range.start.character : 0; - let ec = i == range.end.line ? range.end.character : curr.length; - if (sc == ec) - continue; - arr.push([vscode_languageserver_protocol_1.Range.create(i, sc, i, ec), curr]); - } - for (let [r, line] of arr) { - let start = string_1.byteIndex(line, r.start.character) + 1; - let end = string_1.byteIndex(line, r.end.character) + 1; - res.push([r.start.line + 1, start, end - start]); - } - return res; - } - /** - * Get WorkspaceFolder of uri - */ - getWorkspaceFolder(uri) { - this.workspaceFolders.sort((a, b) => b.uri.length - a.uri.length); - let filepath = vscode_uri_1.URI.parse(uri).fsPath; - return this.workspaceFolders.find(folder => fs_2.isParentFolder(vscode_uri_1.URI.parse(folder.uri).fsPath, filepath, true)); - } - /** - * Get content from buffer of file by uri. - */ - async readFile(uri) { - let document = this.getDocument(uri); - if (document) { - await document.patchChange(); - return document.content; - } - let u = vscode_uri_1.URI.parse(uri); - if (u.scheme != 'file') - return ''; - let encoding = await this.getFileEncoding(); - return await fs_2.readFile(u.fsPath, encoding); - } - getFilepath(filepath) { - let { cwd } = this; - let rel = path_1.default.relative(cwd, filepath); - return rel.startsWith('..') ? filepath : rel; - } - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - onWillSaveUntil(callback, thisArg, clientId) { - return this.willSaveUntilHandler.addCallback(callback, thisArg, clientId); - } - /** - * Echo lines. - */ - async echoLines(lines, truncate = false) { - let { nvim } = this; - let cmdHeight = this.env.cmdheight; - if (lines.length > cmdHeight && truncate) { - lines = lines.slice(0, cmdHeight); - } - let maxLen = this.env.columns - 12; - lines = lines.map(line => { - line = line.replace(/\n/g, ' '); - if (truncate) - line = line.slice(0, maxLen); - return line; - }); - if (truncate && lines.length == cmdHeight) { - let last = lines[lines.length - 1]; - lines[cmdHeight - 1] = `${last.length == maxLen ? last.slice(0, -4) : last} ...`; - } - await nvim.call('coc#util#echo_lines', [lines]); - } - /** - * Show message in vim. - */ - showMessage(msg, identify = 'more') { - if (this.mutex.busy || !this.nvim) - return; - let { messageLevel } = this; - let method = process.env.VIM_NODE_RPC == '1' ? 'callTimer' : 'call'; - let hl = 'Error'; - let level = types_1.MessageLevel.Error; - switch (identify) { - case 'more': - level = types_1.MessageLevel.More; - hl = 'MoreMsg'; - break; - case 'warning': - level = types_1.MessageLevel.Warning; - hl = 'WarningMsg'; - break; - } - if (level >= messageLevel) { - this.nvim[method]('coc#util#echo_messages', [hl, ('[coc.nvim] ' + msg).split('\n')], true); - } - } - /** - * Current document. - */ - get document() { - let { bufnr } = this; - if (bufnr == null) - return null; - if (this.buffers.has(bufnr)) { - return Promise.resolve(this.buffers.get(bufnr)); - } - if (!this.creatingSources.has(bufnr)) { - this.onBufCreate(bufnr).logError(); - } - return new Promise(resolve => { - let disposable = this.onDidOpenTextDocument(doc => { - disposable.dispose(); - resolve(this.getDocument(doc.uri)); - }); - }); - } - /** - * Get current cursor position. - */ - async getCursorPosition() { - let [line, character] = await this.nvim.call('coc#util#cursor'); - return vscode_languageserver_protocol_1.Position.create(line, character); - } - /** - * Get current document and position. - */ - async getCurrentState() { - let document = await this.document; - let position = await this.getCursorPosition(); - return { - document: document.textDocument, - position - }; - } - /** - * Get format options - */ - async getFormatOptions(uri) { - let doc; - if (uri) - doc = this.getDocument(uri); - let bufnr = doc ? doc.bufnr : 0; - let [tabSize, insertSpaces] = await this.nvim.call('coc#util#get_format_opts', [bufnr]); - return { - tabSize, - insertSpaces: insertSpaces == 1 - }; - } - /** - * Jump to location. - */ - async jumpTo(uri, position, openCommand) { - const preferences = this.getConfiguration('coc.preferences'); - let jumpCommand = openCommand || preferences.get('jumpCommand', 'edit'); - let { nvim } = this; - let doc = this.getDocument(uri); - let bufnr = doc ? doc.bufnr : -1; - if (bufnr != -1 && jumpCommand == 'edit') { - // use buffer command since edit command would reload the buffer - nvim.pauseNotification(); - nvim.command(`silent! normal! m'`, true); - nvim.command(`buffer ${bufnr}`, true); - if (position) { - let line = doc.getline(position.line); - let col = string_1.byteLength(line.slice(0, position.character)) + 1; - nvim.call('cursor', [position.line + 1, col], true); - } - if (this.isVim) - nvim.command('redraw', true); - await nvim.resumeNotification(); - } - else { - let { fsPath, scheme } = vscode_uri_1.URI.parse(uri); - let pos = position == null ? null : [position.line, position.character]; - if (scheme == 'file') { - let bufname = fs_2.fixDriver(path_1.default.normalize(fsPath)); - await this.nvim.call('coc#util#jump', [jumpCommand, bufname, pos]); - } - else { - await this.nvim.call('coc#util#jump', [jumpCommand, uri, pos]); - } - } - } - /** - * Move cursor to position. - */ - async moveTo(position) { - await this.nvim.call('coc#util#jumpTo', [position.line, position.character]); - if (this.isVim) - this.nvim.command('redraw', true); - } - /** - * Create a file in vim and disk - */ - async createFile(filepath, opts = {}) { - let stat = await fs_2.statAsync(filepath); - if (stat && !opts.overwrite && !opts.ignoreIfExists) { - this.showMessage(`${filepath} already exists!`, 'error'); - return; - } - if (!stat || opts.overwrite) { - // directory - if (filepath.endsWith('/')) { - try { - filepath = this.expand(filepath); - await mkdirp_1.default(filepath); - } - catch (e) { - this.showMessage(`Can't create ${filepath}: ${e.message}`, 'error'); - } - } - else { - let uri = vscode_uri_1.URI.file(filepath).toString(); - let doc = this.getDocument(uri); - if (doc) - return; - if (!fs_1.default.existsSync(path_1.default.dirname(filepath))) { - fs_1.default.mkdirSync(path_1.default.dirname(filepath), { recursive: true }); - } - let encoding = await this.getFileEncoding(); - fs_1.default.writeFileSync(filepath, '', encoding || ''); - await this.loadFile(uri); - } - } - } - /** - * Load uri as document. - */ - async loadFile(uri) { - let doc = this.getDocument(uri); - if (doc) - return doc; - let { nvim } = this; - let filepath = uri.startsWith('file') ? vscode_uri_1.URI.parse(uri).fsPath : uri; - nvim.call('coc#util#open_files', [[filepath]], true); - return await new Promise((resolve, reject) => { - let disposable = this.onDidOpenTextDocument(textDocument => { - let fsPath = vscode_uri_1.URI.parse(textDocument.uri).fsPath; - if (textDocument.uri == uri || fsPath == filepath) { - clearTimeout(timer); - disposable.dispose(); - resolve(this.getDocument(uri)); - } - }); - let timer = setTimeout(() => { - disposable.dispose(); - reject(new Error(`Create document ${uri} timeout after 1s.`)); - }, 1000); - }); - } - /** - * Load the files that not loaded - */ - async loadFiles(uris) { - uris = uris.filter(uri => this.getDocument(uri) == null); - if (!uris.length) - return; - let bufnrs = await this.nvim.call('coc#util#open_files', [uris.map(u => vscode_uri_1.URI.parse(u).fsPath)]); - let create = bufnrs.filter(bufnr => this.getDocument(bufnr) == null); - if (!create.length) - return; - create.map(bufnr => this.onBufCreate(bufnr).logError()); - return new Promise((resolve, reject) => { - let timer = setTimeout(() => { - disposable.dispose(); - reject(new Error(`Create document timeout after 2s.`)); - }, 2000); - let disposable = this.onDidOpenTextDocument(() => { - if (uris.every(uri => this.getDocument(uri) != null)) { - clearTimeout(timer); - disposable.dispose(); - resolve(); - } - }); - }); - } - /** - * Rename file in vim and disk - */ - async renameFile(oldPath, newPath, opts = {}) { - let { overwrite, ignoreIfExists } = opts; - let { nvim } = this; - try { - let stat = await fs_2.statAsync(newPath); - if (stat && !overwrite && !ignoreIfExists) { - throw new Error(`${newPath} already exists`); - } - if (!stat || overwrite) { - let uri = vscode_uri_1.URI.file(oldPath).toString(); - let newUri = vscode_uri_1.URI.file(newPath).toString(); - let doc = this.getDocument(uri); - let isCurrent = doc.bufnr == this.bufnr; - let newDoc = this.getDocument(newUri); - if (newDoc) - await this.nvim.command(`silent ${newDoc.bufnr}bwipeout!`); - if (doc != null) { - let content = doc.getDocumentContent(); - let encoding = await doc.buffer.getOption('fileencoding'); - await util_1.default.promisify(fs_1.default.writeFile)(newPath, content, { encoding }); - // open renamed file - if (!isCurrent) { - await nvim.call('coc#util#open_files', [[newPath]]); - await nvim.command(`silent ${doc.bufnr}bwipeout!`); - } - else { - let view = await nvim.call('winsaveview'); - nvim.pauseNotification(); - nvim.call('coc#util#open_file', ['keepalt edit', newPath], true); - nvim.command(`silent ${doc.bufnr}bwipeout!`, true); - nvim.call('winrestview', [view], true); - await nvim.resumeNotification(); - } - // avoid vim detect file unlink - await util_1.default.promisify(fs_1.default.unlink)(oldPath); - } - else { - await fs_2.renameAsync(oldPath, newPath); - } - } - } - catch (e) { - this.showMessage(`Rename error: ${e.message}`, 'error'); - } - } - /** - * Delete file from vim and disk. - */ - async deleteFile(filepath, opts = {}) { - let { ignoreIfNotExists, recursive } = opts; - let stat = await fs_2.statAsync(filepath.replace(/\/$/, '')); - let isDir = stat && stat.isDirectory(); - if (filepath.endsWith('/') && !isDir) { - this.showMessage(`${filepath} is not directory`, 'error'); - return; - } - if (!stat && !ignoreIfNotExists) { - this.showMessage(`${filepath} not exists`, 'error'); - return; - } - if (stat == null) - return; - if (isDir && !recursive) { - this.showMessage(`Can't remove directory, recursive not set`, 'error'); - return; - } - try { - if (isDir && recursive) { - rimraf_1.default.sync(filepath); - } - else if (isDir) { - await util_1.default.promisify(fs_1.default.rmdir)(filepath); - } - else { - await util_1.default.promisify(fs_1.default.unlink)(filepath); - } - if (!isDir) { - let uri = vscode_uri_1.URI.file(filepath).toString(); - let doc = this.getDocument(uri); - if (doc) - await this.nvim.command(`silent! bwipeout! ${doc.bufnr}`); - } - } - catch (e) { - this.showMessage(`Error on delete ${filepath}: ${e.message}`, 'error'); - } - } - /** - * Open resource by uri - */ - async openResource(uri) { - let { nvim } = this; - // not supported - if (uri.startsWith('http')) { - await nvim.call('coc#util#open_url', uri); - return; - } - let wildignore = await nvim.getOption('wildignore'); - await nvim.setOption('wildignore', ''); - await this.jumpTo(uri); - await nvim.setOption('wildignore', wildignore); - } - /** - * Create a new output channel - */ - createOutputChannel(name) { - return channels_1.default.create(name, this.nvim); - } - /** - * Reveal buffer of output channel. - */ - showOutputChannel(name, preserveFocus) { - channels_1.default.show(name, preserveFocus); - } - /** - * Resovle module from yarn or npm. - */ - async resolveModule(name) { - return await this.resolver.resolveModule(name); - } - /** - * Run nodejs command - */ - async runCommand(cmd, cwd, timeout) { - cwd = cwd || this.cwd; - return index_1.runCommand(cmd, { cwd }, timeout); - } - /** - * Run command in vim terminal for result - */ - async runTerminalCommand(cmd, cwd = this.cwd, keepfocus = false) { - return await this.nvim.callAsync('coc#util#run_terminal', { cmd, cwd, keepfocus: keepfocus ? 1 : 0 }); - } - /** - * Open terminal buffer with cmd & opts - */ - async openTerminal(cmd, opts = {}) { - let bufnr = await this.nvim.call('coc#util#open_terminal', Object.assign({ cmd }, opts)); - return bufnr; - } - /** - * Expand filepath with `~` and/or environment placeholders - */ - expand(filepath) { - if (!filepath) - return filepath; - if (filepath.startsWith('~')) { - filepath = os_1.default.homedir() + filepath.slice(1); - } - if (filepath.includes('$')) { - let doc = this.getDocument(this.bufnr); - let fsPath = doc ? vscode_uri_1.URI.parse(doc.uri).fsPath : ''; - filepath = filepath.replace(/\$\{(.*?)\}/g, (match, name) => { - if (name.startsWith('env:')) { - let key = name.split(':')[1]; - let val = key ? process.env[key] : ''; - return val; - } - switch (name) { - case 'workspace': - case 'workspaceRoot': - case 'workspaceFolder': - return this.root; - case 'workspaceFolderBasename': - return path_1.default.dirname(this.root); - case 'cwd': - return this.cwd; - case 'file': - return fsPath; - case 'fileDirname': - return fsPath ? path_1.default.dirname(fsPath) : ''; - case 'fileExtname': - return fsPath ? path_1.default.extname(fsPath) : ''; - case 'fileBasename': - return fsPath ? path_1.default.basename(fsPath) : ''; - case 'fileBasenameNoExtension': { - let basename = fsPath ? path_1.default.basename(fsPath) : ''; - return basename ? basename.slice(0, basename.length - path_1.default.extname(basename).length) : ''; - } - default: - return match; - } - }); - filepath = filepath.replace(/\$[\w]+/g, match => { - if (match == '$HOME') - return os_1.default.homedir(); - return process.env[match.slice(1)] || match; - }); - } - return filepath; - } - async createTerminal(opts) { - let cmd = opts.shellPath; - let args = opts.shellArgs; - if (!cmd) - cmd = await this.nvim.getOption('shell'); - let terminal = new terminal_1.default(cmd, args || [], this.nvim, opts.name); - await terminal.start(opts.cwd || this.cwd, opts.env); - this.terminals.set(terminal.bufnr, terminal); - this._onDidOpenTerminal.fire(terminal); - return terminal; - } - /** - * Show quickpick - */ - async showQuickpick(items, placeholder = 'Choose by number') { - let release = await this.mutex.acquire(); - try { - let title = placeholder + ':'; - items = items.map((s, idx) => `${idx + 1}. ${s}`); - let res = await this.nvim.callAsync('coc#util#quickpick', [title, items]); - release(); - let n = parseInt(res, 10); - if (isNaN(n) || n <= 0 || n > items.length) - return -1; - return n - 1; - } - catch (e) { - release(); - return -1; - } - } - async menuPick(items, title) { - if (this.floatSupported) { - let { menu } = this; - menu.show(items, title); - let res = await new Promise(resolve => { - let disposables = []; - menu.onDidCancel(() => { - index_1.disposeAll(disposables); - resolve(-1); - }, null, disposables); - menu.onDidChoose(idx => { - index_1.disposeAll(disposables); - resolve(idx); - }, null, disposables); - }); - return res; - } - return await this.showQuickpick(items); - } - /** - * Prompt for confirm action. - */ - async showPrompt(title) { - let release = await this.mutex.acquire(); - try { - let res = await this.nvim.callAsync('coc#util#prompt', [title]); - release(); - return !!res; - } - catch (e) { - release(); - return false; - } - } - async callAsync(method, args) { - if (this.isNvim) - return await this.nvim.call(method, args); - return await this.nvim.callAsync('coc#util#with_callback', [method, args]); - } - /** - * Request input from user - */ - async requestInput(title, defaultValue) { - let { nvim } = this; - const preferences = this.getConfiguration('coc.preferences'); - if (this.isNvim && semver_1.default.gte(this.env.version, '0.4.3') && preferences.get('promptInput', true)) { - let arr = await nvim.call('coc#float#create_prompt_win', [title, defaultValue || '']); - if (!arr || arr.length == 0) - return null; - let [bufnr, winid] = arr; - let cleanUp = () => { - nvim.pauseNotification(); - nvim.call('coc#float#close', [winid], true); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true); - }; - let res = await new Promise(resolve => { - let disposables = []; - events_1.default.on('BufUnload', nr => { - if (nr == bufnr) { - index_1.disposeAll(disposables); - cleanUp(); - resolve(null); - } - }, null, disposables); - events_1.default.on('PromptInsert', value => { - if (!value) { - setTimeout(() => { - this.showMessage('Empty word, canceled', 'warning'); - }, 30); - resolve(null); - } - else { - resolve(value); - } - }, null, disposables); - }); - return res; - } - let res = await this.callAsync('input', [title + ': ', defaultValue || '']); - nvim.command('normal! :', true); - if (!res) { - this.showMessage('Empty word, canceled', 'warning'); - return null; - } - return res; - } - /** - * registerTextDocumentContentProvider - */ - registerTextDocumentContentProvider(scheme, provider) { - this.schemeProviderMap.set(scheme, provider); - this.setupDynamicAutocmd(); - let disposables = []; - if (provider.onDidChange) { - provider.onDidChange(async (uri) => { - let doc = this.getDocument(uri.toString()); - if (doc) { - let { buffer } = doc; - let tokenSource = new vscode_languageserver_protocol_1.CancellationTokenSource(); - let content = await Promise.resolve(provider.provideTextDocumentContent(uri, tokenSource.token)); - await buffer.setLines(content.split('\n'), { - start: 0, - end: -1, - strictIndexing: false - }); - } - }, null, disposables); - } - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.schemeProviderMap.delete(scheme); - index_1.disposeAll(disposables); - this.setupDynamicAutocmd(); - }); - } - /** - * Register unique keymap uses `(coc-{key})` as lhs - * Throw error when {key} already exists. - * - * @param {MapMode[]} modes - array of 'n' | 'i' | 'v' | 'x' | 's' | 'o' - * @param {string} key - unique name - * @param {Function} fn - callback function - * @param {Partial} opts - * @returns {Disposable} - */ - registerKeymap(modes, key, fn, opts = {}) { - if (!key) - throw new Error(`Invalid key ${key} of registerKeymap`); - if (this.keymaps.has(key)) - throw new Error(`${key} already exists.`); - opts = Object.assign({ sync: true, cancel: true, silent: true, repeat: false }, opts); - let { nvim } = this; - this.keymaps.set(key, [fn, !!opts.repeat]); - let method = opts.sync ? 'request' : 'notify'; - let silent = opts.silent ? '' : ''; - for (let m of modes) { - if (m == 'i') { - nvim.command(`inoremap ${silent} (coc-${key}) coc#_insert_key('${method}', '${key}', ${opts.cancel ? 1 : 0})`, true); - } - else { - let modify = index_1.getKeymapModifier(m); - nvim.command(`${m}noremap ${silent} (coc-${key}) :${modify}call coc#rpc#${method}('doKeymap', ['${key}'])`, true); - } - } - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.keymaps.delete(key); - for (let m of modes) { - nvim.command(`${m}unmap (coc-${key})`, true); - } - }); - } - /** - * Register expr keymap. - */ - registerExprKeymap(mode, key, fn, buffer = false) { - if (!key) - return; - let id = `${mode}${global.Buffer.from(key).toString('base64')}${buffer ? '1' : '0'}`; - let { nvim } = this; - this.keymaps.set(id, [fn, false]); - if (mode == 'i') { - nvim.command(`inoremap ${buffer ? '' : ''} ${key} coc#_insert_key('request', '${id}')`, true); - } - else { - nvim.command(`${mode}noremap ${buffer ? '' : ''} ${key} coc#rpc#request('doKeymap', ['${id}'])`, true); - } - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.keymaps.delete(id); - nvim.command(`${mode}unmap ${buffer ? '' : ''} ${key}`, true); - }); - } - registerLocalKeymap(mode, key, fn, notify = false) { - let id = uuid_1.v1(); - let { nvim } = this; - this.keymaps.set(id, [fn, false]); - let modify = index_1.getKeymapModifier(mode); - nvim.command(`${mode}noremap ${key} :${modify}call coc#rpc#${notify ? 'notify' : 'request'}('doKeymap', ['${id}'])`, true); - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.keymaps.delete(id); - nvim.command(`${mode}unmap ${key}`, true); - }); - } - /** - * Create StatusBarItem - */ - createStatusBarItem(priority = 0, opt = {}) { - if (!this.statusLine) { - let fn = () => { }; - return { text: '', show: fn, dispose: fn, hide: fn, priority: 0, isProgress: false }; - } - return this.statusLine.createStatusBarItem(priority, opt.progress || false); - } - dispose() { - this._disposed = true; - channels_1.default.dispose(); - for (let doc of this.documents) { - doc.detach(); - } - index_1.disposeAll(this.disposables); - watchman_1.default.dispose(); - this.configurations.dispose(); - this.buffers.clear(); - if (this.statusLine) - this.statusLine.dispose(); - } - async detach() { - if (!this._attached) - return; - this._attached = false; - for (let bufnr of this.buffers.keys()) { - await events_1.default.fire('BufUnload', [bufnr]); - } - } - /** - * Create DB instance at extension root. - */ - createDatabase(name) { - let root; - if (global.hasOwnProperty('__TEST__')) { - root = path_1.default.join(os_1.default.tmpdir(), `coc-${process.pid}`); - fs_1.default.mkdirSync(root, { recursive: true }); - } - else { - root = path_1.default.dirname(this.env.extensionRoot); - } - let filepath = path_1.default.join(root, name + '.json'); - return new db_1.default(filepath); - } - /** - * Create Task instance that runs in vim. - */ - createTask(id) { - return new task_1.default(this.nvim, id); - } - setupDynamicAutocmd(initialize = false) { - if (!initialize && !this._dynAutocmd) - return; - this._dynAutocmd = true; - let schemes = this.schemeProviderMap.keys(); - let cmds = []; - for (let scheme of schemes) { - cmds.push(`autocmd BufReadCmd,FileReadCmd,SourceCmd ${scheme}://* call coc#rpc#request('CocAutocmd', ['BufReadCmd','${scheme}', expand('')])`); - } - for (let [id, autocmd] of this.autocmds.entries()) { - let args = autocmd.arglist && autocmd.arglist.length ? ', ' + autocmd.arglist.join(', ') : ''; - let event = Array.isArray(autocmd.event) ? autocmd.event.join(',') : autocmd.event; - let pattern = autocmd.pattern != null ? autocmd.pattern : '*'; - if (/\buser\b/i.test(event)) { - pattern = ''; - } - cmds.push(`autocmd ${event} ${pattern} call coc#rpc#${autocmd.request ? 'request' : 'notify'}('doAutocmd', [${id}${args}])`); - } - for (let key of this.watchedOptions) { - cmds.push(`autocmd OptionSet ${key} call coc#rpc#notify('OptionSet',[expand(''), v:option_old, v:option_new])`); - } - let content = ` +var _J=Object.create,Zu=Object.defineProperty,PJ=Object.getPrototypeOf,TJ=Object.prototype.hasOwnProperty,RJ=Object.getOwnPropertyNames,NP=Object.getOwnPropertyDescriptor;var qP=r=>Zu(r,"__esModule",{value:!0});var g=(r,e)=>()=>(e||(e={exports:{}},r(e.exports,e)),e.exports),fo=(r,e)=>{qP(r);for(var t in e)Zu(r,t,{get:e[t],enumerable:!0})},kJ=(r,e,t)=>{if(qP(r),e&&typeof e=="object"||typeof e=="function")for(let i of RJ(e))!TJ.call(r,i)&&i!=="default"&&Zu(r,i,{get:()=>e[i],enumerable:!(t=NP(e,i))||t.enumerable});return r},S=r=>r&&r.__esModule?r:kJ(Zu(r!=null?_J(PJ(r)):{},"default",{value:r,enumerable:!0}),r),Ty=(r,e,t,i)=>{for(var n=i>1?void 0:i?NP(e,t):e,o=r.length-1,s;o>=0;o--)(s=r[o])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&Zu(e,t,n),n};var BP=g((cSe,$P)=>{"use strict";var IJ="Function.prototype.bind called on incompatible ",Ry=Array.prototype.slice,FJ=Object.prototype.toString,AJ="[object Function]";$P.exports=function(e){var t=this;if(typeof t!="function"||FJ.call(t)!==AJ)throw new TypeError(IJ+t);for(var i=Ry.call(arguments,1),n,o=function(){if(this instanceof n){var c=t.apply(this,i.concat(Ry.call(arguments)));return Object(c)===c?c:this}else return t.apply(e,i.concat(Ry.call(arguments)))},s=Math.max(0,t.length-i.length),a=[],l=0;l{"use strict";var OJ=BP();jP.exports=Function.prototype.bind||OJ});var ky=g((pSe,UP)=>{"use strict";var WP=Object.prototype.toString;UP.exports=function(e){var t=WP.call(e),i=t==="[object Arguments]";return i||(i=t!=="[object Array]"&&e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&WP.call(e.callee)==="[object Function]"),i}});var ZP=g((dSe,HP)=>{"use strict";var zP;Object.keys||(Qu=Object.prototype.hasOwnProperty,Iy=Object.prototype.toString,GP=ky(),Fy=Object.prototype.propertyIsEnumerable,VP=!Fy.call({toString:null},"toString"),KP=Fy.call(function(){},"prototype"),ec=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],Ed=function(r){var e=r.constructor;return e&&e.prototype===r},JP={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},YP=function(){if(typeof window=="undefined")return!1;for(var r in window)try{if(!JP["$"+r]&&Qu.call(window,r)&&window[r]!==null&&typeof window[r]=="object")try{Ed(window[r])}catch(e){return!0}}catch(e){return!0}return!1}(),XP=function(r){if(typeof window=="undefined"||!YP)return Ed(r);try{return Ed(r)}catch(e){return!1}},zP=function(e){var t=e!==null&&typeof e=="object",i=Iy.call(e)==="[object Function]",n=GP(e),o=t&&Iy.call(e)==="[object String]",s=[];if(!t&&!i&&!n)throw new TypeError("Object.keys called on a non-object");var a=KP&&i;if(o&&e.length>0&&!Qu.call(e,0))for(var l=0;l0)for(var u=0;u{"use strict";var LJ=Array.prototype.slice,MJ=ky(),eT=Object.keys,Cd=eT?function(e){return eT(e)}:ZP(),tT=Object.keys;Cd.shim=function(){if(Object.keys){var e=function(){var t=Object.keys(arguments);return t&&t.length===arguments.length}(1,2);e||(Object.keys=function(i){return MJ(i)?tT(LJ.call(i)):tT(i)})}else Object.keys=Cd;return Object.keys||Cd};QP.exports=Cd});var Fn=g((mSe,iT)=>{"use strict";var NJ=rT(),qJ=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",$J=Object.prototype.toString,BJ=Array.prototype.concat,Ay=Object.defineProperty,jJ=function(r){return typeof r=="function"&&$J.call(r)==="[object Function]"},UJ=function(){var r={};try{Ay(r,"x",{enumerable:!1,value:r});for(var e in r)return!1;return r.x===r}catch(t){return!1}},nT=Ay&&UJ(),WJ=function(r,e,t,i){e in r&&(!jJ(i)||!i())||(nT?Ay(r,e,{configurable:!0,enumerable:!1,value:t,writable:!0}):r[e]=t)},oT=function(r,e){var t=arguments.length>2?arguments[2]:{},i=NJ(e);qJ&&(i=BJ.call(i,Object.getOwnPropertySymbols(e)));for(var n=0;n{"use strict";sT.exports=function(){if(typeof Promise!="function")throw new TypeError("`Promise.prototype.finally` requires a global `Promise` be available.")}});var Oy=g((vSe,aT)=>{"use strict";var lT=Function.prototype.toString,HJ=/^\s*class\b/,uT=function(e){try{var t=lT.call(e);return HJ.test(t)}catch(i){return!1}},zJ=function(e){try{return uT(e)?!1:(lT.call(e),!0)}catch(t){return!1}},GJ=Object.prototype.toString,VJ="[object Function]",KJ="[object GeneratorFunction]",JJ=typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol";aT.exports=function(e){if(!e||typeof e!="function"&&typeof e!="object")return!1;if(typeof e=="function"&&!e.prototype)return!0;if(JJ)return zJ(e);if(uT(e))return!1;var t=GJ.call(e);return t===VJ||t===KJ}});var fT=g((ySe,cT)=>{"use strict";cT.exports=Oy()});var dT=g((bSe,pT)=>{"use strict";pT.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},t=Symbol("test"),i=Object(t);if(typeof t=="string"||Object.prototype.toString.call(t)!=="[object Symbol]"||Object.prototype.toString.call(i)!=="[object Symbol]")return!1;var n=42;e[t]=n;for(t in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,t);if(s.value!==n||s.enumerable!==!0)return!1}return!0}});var Li=g((wSe,hT)=>{"use strict";var mT=global.Symbol,YJ=dT();hT.exports=function(){return typeof mT!="function"||typeof Symbol!="function"||typeof mT("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:YJ()}});var bT=g((xSe,gT)=>{"use strict";var J,tc=TypeError,gs=Object.getOwnPropertyDescriptor;if(gs)try{gs({},"")}catch(r){gs=null}var Ly=function(){throw new tc},XJ=gs?function(){try{return arguments.callee,Ly}catch(r){try{return gs(arguments,"callee").get}catch(e){return Ly}}}():Ly,po=Li()(),Mi=Object.getPrototypeOf||function(r){return r.__proto__},Pd,My=Pd?Mi(Pd):J,vT,Ny=vT?vT.constructor:J,rc,qy=rc?Mi(rc):J,$y=rc?rc():J,By=typeof Uint8Array=="undefined"?J:Mi(Uint8Array),jy={"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?J:ArrayBuffer,"%ArrayBufferPrototype%":typeof ArrayBuffer=="undefined"?J:ArrayBuffer.prototype,"%ArrayIteratorPrototype%":po?Mi([][Symbol.iterator]()):J,"%ArrayPrototype%":Array.prototype,"%ArrayProto_entries%":Array.prototype.entries,"%ArrayProto_forEach%":Array.prototype.forEach,"%ArrayProto_keys%":Array.prototype.keys,"%ArrayProto_values%":Array.prototype.values,"%AsyncFromSyncIteratorPrototype%":J,"%AsyncFunction%":Ny,"%AsyncFunctionPrototype%":Ny?Ny.prototype:J,"%AsyncGenerator%":rc?Mi($y):J,"%AsyncGeneratorFunction%":qy,"%AsyncGeneratorPrototype%":qy?qy.prototype:J,"%AsyncIteratorPrototype%":$y&&po&&Symbol.asyncIterator?$y[Symbol.asyncIterator]():J,"%Atomics%":typeof Atomics=="undefined"?J:Atomics,"%Boolean%":Boolean,"%BooleanPrototype%":Boolean.prototype,"%DataView%":typeof DataView=="undefined"?J:DataView,"%DataViewPrototype%":typeof DataView=="undefined"?J:DataView.prototype,"%Date%":Date,"%DatePrototype%":Date.prototype,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%ErrorPrototype%":Error.prototype,"%eval%":eval,"%EvalError%":EvalError,"%EvalErrorPrototype%":EvalError.prototype,"%Float32Array%":typeof Float32Array=="undefined"?J:Float32Array,"%Float32ArrayPrototype%":typeof Float32Array=="undefined"?J:Float32Array.prototype,"%Float64Array%":typeof Float64Array=="undefined"?J:Float64Array,"%Float64ArrayPrototype%":typeof Float64Array=="undefined"?J:Float64Array.prototype,"%Function%":Function,"%FunctionPrototype%":Function.prototype,"%Generator%":Pd?Mi(Pd()):J,"%GeneratorFunction%":My,"%GeneratorPrototype%":My?My.prototype:J,"%Int8Array%":typeof Int8Array=="undefined"?J:Int8Array,"%Int8ArrayPrototype%":typeof Int8Array=="undefined"?J:Int8Array.prototype,"%Int16Array%":typeof Int16Array=="undefined"?J:Int16Array,"%Int16ArrayPrototype%":typeof Int16Array=="undefined"?J:Int8Array.prototype,"%Int32Array%":typeof Int32Array=="undefined"?J:Int32Array,"%Int32ArrayPrototype%":typeof Int32Array=="undefined"?J:Int32Array.prototype,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":po?Mi(Mi([][Symbol.iterator]())):J,"%JSON%":typeof JSON=="object"?JSON:J,"%JSONParse%":typeof JSON=="object"?JSON.parse:J,"%Map%":typeof Map=="undefined"?J:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!po?J:Mi(new Map()[Symbol.iterator]()),"%MapPrototype%":typeof Map=="undefined"?J:Map.prototype,"%Math%":Math,"%Number%":Number,"%NumberPrototype%":Number.prototype,"%Object%":Object,"%ObjectPrototype%":Object.prototype,"%ObjProto_toString%":Object.prototype.toString,"%ObjProto_valueOf%":Object.prototype.valueOf,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?J:Promise,"%PromisePrototype%":typeof Promise=="undefined"?J:Promise.prototype,"%PromiseProto_then%":typeof Promise=="undefined"?J:Promise.prototype.then,"%Promise_all%":typeof Promise=="undefined"?J:Promise.all,"%Promise_reject%":typeof Promise=="undefined"?J:Promise.reject,"%Promise_resolve%":typeof Promise=="undefined"?J:Promise.resolve,"%Proxy%":typeof Proxy=="undefined"?J:Proxy,"%RangeError%":RangeError,"%RangeErrorPrototype%":RangeError.prototype,"%ReferenceError%":ReferenceError,"%ReferenceErrorPrototype%":ReferenceError.prototype,"%Reflect%":typeof Reflect=="undefined"?J:Reflect,"%RegExp%":RegExp,"%RegExpPrototype%":RegExp.prototype,"%Set%":typeof Set=="undefined"?J:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!po?J:Mi(new Set()[Symbol.iterator]()),"%SetPrototype%":typeof Set=="undefined"?J:Set.prototype,"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?J:SharedArrayBuffer,"%SharedArrayBufferPrototype%":typeof SharedArrayBuffer=="undefined"?J:SharedArrayBuffer.prototype,"%String%":String,"%StringIteratorPrototype%":po?Mi(""[Symbol.iterator]()):J,"%StringPrototype%":String.prototype,"%Symbol%":po?Symbol:J,"%SymbolPrototype%":po?Symbol.prototype:J,"%SyntaxError%":SyntaxError,"%SyntaxErrorPrototype%":SyntaxError.prototype,"%ThrowTypeError%":XJ,"%TypedArray%":By,"%TypedArrayPrototype%":By?By.prototype:J,"%TypeError%":tc,"%TypeErrorPrototype%":tc.prototype,"%Uint8Array%":typeof Uint8Array=="undefined"?J:Uint8Array,"%Uint8ArrayPrototype%":typeof Uint8Array=="undefined"?J:Uint8Array.prototype,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?J:Uint8ClampedArray,"%Uint8ClampedArrayPrototype%":typeof Uint8ClampedArray=="undefined"?J:Uint8ClampedArray.prototype,"%Uint16Array%":typeof Uint16Array=="undefined"?J:Uint16Array,"%Uint16ArrayPrototype%":typeof Uint16Array=="undefined"?J:Uint16Array.prototype,"%Uint32Array%":typeof Uint32Array=="undefined"?J:Uint32Array,"%Uint32ArrayPrototype%":typeof Uint32Array=="undefined"?J:Uint32Array.prototype,"%URIError%":URIError,"%URIErrorPrototype%":URIError.prototype,"%WeakMap%":typeof WeakMap=="undefined"?J:WeakMap,"%WeakMapPrototype%":typeof WeakMap=="undefined"?J:WeakMap.prototype,"%WeakSet%":typeof WeakSet=="undefined"?J:WeakSet,"%WeakSetPrototype%":typeof WeakSet=="undefined"?J:WeakSet.prototype},ZJ=un(),yT=ZJ.call(Function.call,String.prototype.replace),QJ=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,eY=/\\(\\)?/g,tY=function(e){var t=[];return yT(e,QJ,function(i,n,o,s){t[t.length]=o?yT(s,eY,"$1"):n||i}),t},rY=function(e,t){if(!(e in jy))throw new SyntaxError("intrinsic "+e+" does not exist!");if(typeof jy[e]=="undefined"&&!t)throw new tc("intrinsic "+e+" exists, but is not available. Please file an issue!");return jy[e]};gT.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new TypeError('"allowMissing" argument must be a boolean');for(var i=tY(e),n=rY("%"+(i.length>0?i[0]:"")+"%",t),o=1;o=i.length){var s=gs(n,i[o]);if(!t&&!(i[o]in n))throw new tc("base intrinsic for "+e+" exists, but the property is not available.");n=s?s.get||s.value:n[i[o]]}else n=n[i[o]];return n}});var xT=g((DSe,wT)=>{"use strict";wT.exports=function(e){return typeof e=="function"&&!!e.prototype}});var ST=g((SSe,DT)=>{"use strict";DT.exports=function(e){if(e===null)return"Null";if(typeof e=="undefined")return"Undefined";if(typeof e=="function"||typeof e=="object")return"Object";if(typeof e=="number")return"Number";if(typeof e=="boolean")return"Boolean";if(typeof e=="string")return"String"}});var Uy=g((ESe,ET)=>{"use strict";var iY=ST();ET.exports=function(e){return typeof e=="symbol"?"Symbol":iY(e)}});var RT=g((CSe,CT)=>{"use strict";var _T=bT(),PT=_T("%Symbol.species%",!0),Wy=_T("%TypeError%"),nY=xT(),TT=Uy();CT.exports=function(e,t){if(TT(e)!=="Object")throw new Wy("Assertion failed: Type(O) is not Object");var i=e.constructor;if(typeof i=="undefined")return t;if(TT(i)!=="Object")throw new Wy("O.constructor is not an Object");var n=PT?i[PT]:void 0;if(n==null)return t;if(nY(n))return n;throw new Wy("no constructor found")}});var Gy=g((_Se,kT)=>{"use strict";var oY=_d();oY();var sY=fT(),aY=RT(),lY=Uy(),IT=function(e,t){return new e(function(i){i(t)})},uY=Promise,cY=function(e,t){return function(i){var n=t(),o=IT(e,n),s=function(){return i};return o.then(s)}},fY=function(e,t){return function(i){var n=t(),o=IT(e,n),s=function(){throw i};return o.then(s)}},Hy=function(e){var t=this;if(lY(t)!=="Object")throw new TypeError("receiver is not an Object");var i=aY(t,uY),n=e,o=e;return sY(e)&&(n=cY(i,e),o=fY(i,e)),t.then(n,o)};Object.getOwnPropertyDescriptor&&(zy=Object.getOwnPropertyDescriptor(Hy,"name"),zy&&zy.configurable&&Object.defineProperty(Hy,"name",{configurable:!0,value:"finally"}));var zy;kT.exports=Hy});var Vy=g((PSe,FT)=>{"use strict";var pY=_d(),dY=Gy();FT.exports=function(){return pY(),typeof Promise.prototype.finally=="function"?Promise.prototype.finally:dY}});var OT=g((TSe,AT)=>{"use strict";var hY=_d(),mY=Vy(),gY=Fn();AT.exports=function(){hY();var e=mY();return gY(Promise.prototype,{finally:e},{finally:function(){return Promise.prototype.finally!==e}}),e}});var qT=g((RSe,LT)=>{"use strict";var vY=un(),yY=Fn(),bY=Gy(),MT=Vy(),wY=OT(),NT=vY.call(Function.call,MT());yY(NT,{getPolyfill:MT,implementation:bY,shim:wY});LT.exports=NT});var BT=g((kSe,$T)=>{var Ma=1e3,Na=Ma*60,qa=Na*60,vs=qa*24,xY=vs*7,DY=vs*365.25;$T.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return SY(r);if(t==="number"&&isFinite(r))return e.long?CY(r):EY(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function SY(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!!e){var t=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*DY;case"weeks":case"week":case"w":return t*xY;case"days":case"day":case"d":return t*vs;case"hours":case"hour":case"hrs":case"hr":case"h":return t*qa;case"minutes":case"minute":case"mins":case"min":case"m":return t*Na;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ma;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function EY(r){var e=Math.abs(r);return e>=vs?Math.round(r/vs)+"d":e>=qa?Math.round(r/qa)+"h":e>=Na?Math.round(r/Na)+"m":e>=Ma?Math.round(r/Ma)+"s":r+"ms"}function CY(r){var e=Math.abs(r);return e>=vs?Td(r,e,vs,"day"):e>=qa?Td(r,e,qa,"hour"):e>=Na?Td(r,e,Na,"minute"):e>=Ma?Td(r,e,Ma,"second"):r+" ms"}function Td(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var Ky=g((ISe,jT)=>{function _Y(r){t.debug=t,t.default=t,t.coerce=u,t.disable=s,t.enable=o,t.enabled=a,t.humanize=BT(),Object.keys(r).forEach(c=>{t[c]=r[c]}),t.instances=[],t.names=[],t.skips=[],t.formatters={};function e(c){let f=0;for(let p=0;p{if(w==="%%")return w;v++;let P=t.formatters[E];if(typeof P=="function"){let k=d[v];w=P.call(h,k),d.splice(v,1),v--}return w}),t.formatArgs.call(h,d),(h.log||t.log).apply(h,d)}return p.namespace=c,p.enabled=t.enabled(c),p.useColors=t.useColors(),p.color=e(c),p.destroy=i,p.extend=n,typeof t.init=="function"&&t.init(p),t.instances.push(p),p}function i(){let c=t.instances.indexOf(this);return c!==-1?(t.instances.splice(c,1),!0):!1}function n(c,f){let p=t(this.namespace+(typeof f=="undefined"?":":f)+c);return p.log=this.log,p}function o(c){t.save(c),t.names=[],t.skips=[];let f,p=(typeof c=="string"?c:"").split(/[\s,]+/),d=p.length;for(f=0;f"-"+f)].join(",");return t.enable(""),c}function a(c){if(c[c.length-1]==="*")return!0;let f,p;for(f=0,p=t.skips.length;f{ai.log=PY;ai.formatArgs=TY;ai.save=RY;ai.load=kY;ai.useColors=IY;ai.storage=FY();ai.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function IY(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function TY(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Rd.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,i=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(i=t))}),r.splice(i,0,e)}function PY(...r){return typeof console=="object"&&console.log&&console.log(...r)}function RY(r){try{r?ai.storage.setItem("debug",r):ai.storage.removeItem("debug")}catch(e){}}function kY(){let r;try{r=ai.storage.getItem("debug")}catch(e){}return!r&&typeof process!="undefined"&&"env"in process&&(r=process.env.DEBUG),r}function FY(){try{return localStorage}catch(r){}}Rd.exports=Ky()(ai);var{formatters:AY}=Rd.exports;AY.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var HT=g((FSe,WT)=>{"use strict";WT.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),n=e.indexOf("--");return i!==-1&&(n===-1||i{"use strict";var OY=require("os"),GT=require("tty"),li=HT(),{env:Pt}=process,ho;li("no-color")||li("no-colors")||li("color=false")||li("color=never")?ho=0:(li("color")||li("colors")||li("color=true")||li("color=always"))&&(ho=1);"FORCE_COLOR"in Pt&&(Pt.FORCE_COLOR==="true"?ho=1:Pt.FORCE_COLOR==="false"?ho=0:ho=Pt.FORCE_COLOR.length===0?1:Math.min(parseInt(Pt.FORCE_COLOR,10),3));function Jy(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Yy(r,e){if(ho===0)return 0;if(li("color=16m")||li("color=full")||li("color=truecolor"))return 3;if(li("color=256"))return 2;if(r&&!e&&ho===void 0)return 0;let t=ho||0;if(Pt.TERM==="dumb")return t;if(process.platform==="win32"){let i=OY.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Pt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(i=>i in Pt)||Pt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in Pt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Pt.TEAMCITY_VERSION)?1:0;if("GITHUB_ACTIONS"in Pt)return 1;if(Pt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Pt){let i=parseInt((Pt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Pt.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Pt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Pt.TERM)||"COLORTERM"in Pt?1:t}function LY(r){let e=Yy(r,r&&r.isTTY);return Jy(e)}zT.exports={supportsColor:LY,stdout:Jy(Yy(!0,GT.isatty(1))),stderr:Jy(Yy(!0,GT.isatty(2)))}});var JT=g((Qt,kd)=>{var MY=require("tty"),Xy=require("util");Qt.init=NY;Qt.log=qY;Qt.formatArgs=$Y;Qt.save=BY;Qt.load=jY;Qt.useColors=UY;Qt.colors=[6,2,3,4,5,1];try{let r=VT();r&&(r.stderr||r).level>=2&&(Qt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(r){}Qt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),i=process.env[e];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),r[t]=i,r},{});function UY(){return"colors"in Qt.inspectOpts?Boolean(Qt.inspectOpts.colors):MY.isatty(process.stderr.fd)}function $Y(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,n="[3"+(i<8?i:"8;5;"+i),o=` ${n};1m${e} `;r[0]=o+r[0].split(` +`).join(` +`+o),r.push(n+"m+"+kd.exports.humanize(this.diff)+"")}else r[0]=WY()+e+" "+r[0]}function WY(){return Qt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function qY(...r){return process.stderr.write(Xy.format(...r)+` +`)}function BY(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function jY(){return process.env.DEBUG}function NY(r){r.inspectOpts={};let e=Object.keys(Qt.inspectOpts);for(let t=0;t{typeof process=="undefined"||process.type==="renderer"||process.browser===!0||process.__nwjs?Zy.exports=UT():Zy.exports=JT()});var XT=g((LSe,YT)=>{"use strict";YT.exports=HY;function HY(r){if(r=r||{},r.circles)return zY(r);return r.proto?i:t;function e(n,o){for(var s=Object.keys(n),a=new Array(s.length),l=0;l{var GY=require("util"),ys=gt()("log4js:configuration"),Id=[],Fd=[],QT=r=>!r,eR=r=>r&&typeof r=="object"&&!Array.isArray(r),VY=r=>/^[A-Za-z][A-Za-z0-9_]*$/g.test(r),KY=r=>r&&typeof r=="number"&&Number.isInteger(r),JY=r=>{Fd.push(r),ys(`Added listener, now ${Fd.length} listeners`)},YY=r=>{Id.push(r),ys(`Added pre-processing listener, now ${Id.length} listeners`)},tR=(r,e,t)=>{(Array.isArray(e)?e:[e]).forEach(n=>{if(n)throw new Error(`Problem with log4js configuration: (${GY.inspect(r,{depth:5})}) - ${t}`)})},XY=r=>{ys("New configuration to be validated: ",r),tR(r,QT(eR(r)),"must be an object."),ys(`Calling pre-processing listeners (${Id.length})`),Id.forEach(e=>e(r)),ys("Configuration pre-processing finished."),ys(`Calling configuration listeners (${Fd.length})`),Fd.forEach(e=>e(r)),ys("Configuration finished.")};ZT.exports={configure:XY,addListener:JY,addPreProcessingListener:YY,throwExceptionIf:tR,anObject:eR,anInteger:KY,validIdentifier:VY,not:QT}});var nR=g((NSe,ui)=>{"use strict";function rR(r,e){for(var t=r.toString();t.length-1?n:o,a=ws(e.getHours()),l=ws(e.getMinutes()),u=ws(e.getSeconds()),c=rR(e.getMilliseconds(),3),f=ZY(e.getTimezoneOffset()),p=r.replace(/dd/g,t).replace(/MM/g,i).replace(/y{1,4}/g,s).replace(/hh/g,a).replace(/mm/g,l).replace(/ss/g,u).replace(/SSS/g,c).replace(/O/g,f);return p}function xs(r,e,t,i){r["set"+(i?"":"UTC")+e](t)}function QY(r,e,t){var i=r.indexOf("O")<0,n=[{pattern:/y{1,4}/,regexp:"\\d{1,4}",fn:function(c,f){xs(c,"FullYear",f,i)}},{pattern:/MM/,regexp:"\\d{1,2}",fn:function(c,f){xs(c,"Month",f-1,i)}},{pattern:/dd/,regexp:"\\d{1,2}",fn:function(c,f){xs(c,"Date",f,i)}},{pattern:/hh/,regexp:"\\d{1,2}",fn:function(c,f){xs(c,"Hours",f,i)}},{pattern:/mm/,regexp:"\\d\\d",fn:function(c,f){xs(c,"Minutes",f,i)}},{pattern:/ss/,regexp:"\\d\\d",fn:function(c,f){xs(c,"Seconds",f,i)}},{pattern:/SSS/,regexp:"\\d\\d\\d",fn:function(c,f){xs(c,"Milliseconds",f,i)}},{pattern:/O/,regexp:"[+-]\\d{3,4}|Z",fn:function(c,f){f==="Z"&&(f=0);var p=Math.abs(f),d=(f>0?-1:1)*(p%100+Math.floor(p/100)*60);c.setUTCMinutes(c.getUTCMinutes()+d)}}],o=n.reduce(function(c,f){return f.pattern.test(c.regexp)?(f.index=c.regexp.match(f.pattern).index,c.regexp=c.regexp.replace(f.pattern,"("+f.regexp+")")):f.index=-1,c},{regexp:r,index:[]}),s=n.filter(function(c){return c.index>-1});s.sort(function(c,f){return c.index-f.index});var a=new RegExp(o.regexp),l=a.exec(e);if(l){var u=t||ui.exports.now();return s.forEach(function(c,f){c.fn(u,l[f+1])}),u}throw new Error("String '"+e+"' could not be parsed as '"+r+"'")}function eX(r,e,t){if(!r)throw new Error("pattern must be supplied");return QY(r,e,t)}function tX(){return new Date}ui.exports=iR;ui.exports.asString=iR;ui.exports.parse=eX;ui.exports.now=tX;ui.exports.ISO8601_FORMAT="yyyy-MM-ddThh:mm:ss.SSS";ui.exports.ISO8601_WITH_TZ_OFFSET_FORMAT="yyyy-MM-ddThh:mm:ss.SSSO";ui.exports.DATETIME_FORMAT="dd MM yyyy hh:mm:ss.SSS";ui.exports.ABSOLUTETIME_FORMAT="hh:mm:ss.SSS"});var eb=g((qSe,oR)=>{var mo=nR(),sR=require("os"),ic=require("util"),aR=require("path"),lR={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[90,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[91,39],yellow:[33,39]};function uR(r){return r?`[${lR[r][0]}m`:""}function cR(r){return r?`[${lR[r][1]}m`:""}function rX(r,e){return uR(e)+r+cR(e)}function fR(r,e){return rX(ic.format("[%s] [%s] %s - ",mo.asString(r.startTime),r.level.toString(),r.categoryName),e)}function pR(r){return fR(r)+ic.format(...r.data)}function Ad(r){return fR(r,r.level.colour)+ic.format(...r.data)}function dR(r){return ic.format(...r.data)}function hR(r){return r.data[0]}function mR(r,e){let t="%r %p %c - %m%n",i=/%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/;r=r||t;function n(R,F){let q=R.categoryName;if(F){let K=parseInt(F,10),ae=q.split(".");KK&&(q=ae.slice(-K).join(aR.sep))}return q}function w(R){return R.lineNumber?`${R.lineNumber}`:""}function E(R){return R.columnNumber?`${R.columnNumber}`:""}function P(R){return R.callStack||""}let k={c:n,d:o,h:s,m:a,n:l,p:u,r:c,"[":f,"]":p,y:m,z:h,"%":d,x:y,X:v,f:x,l:w,o:E,s:P};function _(R,F,q){return k[R](F,q)}function O(R,F){let q;return R?(q=parseInt(R.substr(1),10),q>0?F.slice(0,q):F.slice(q)):F}function I(R,F){let q;if(R)if(R.charAt(0)==="-")for(q=parseInt(R.substr(1),10);F.length{var vt=bs(),vR=["white","grey","black","blue","cyan","green","magenta","red","yellow"],Tt=class{constructor(e,t,i){this.level=e,this.levelStr=t,this.colour=i}toString(){return this.levelStr}static getLevel(e,t){return e?e instanceof Tt?e:(e instanceof Object&&e.levelStr&&(e=e.levelStr),Tt[e.toString().toUpperCase()]||t):t}static addLevels(e){e&&(Object.keys(e).forEach(i=>{let n=i.toUpperCase();Tt[n]=new Tt(e[i].value,n,e[i].colour);let o=Tt.levels.findIndex(s=>s.levelStr===n);o>-1?Tt.levels[o]=Tt[n]:Tt.levels.push(Tt[n])}),Tt.levels.sort((i,n)=>i.level-n.level))}isLessThanOrEqualTo(e){return typeof e=="string"&&(e=Tt.getLevel(e)),this.level<=e.level}isGreaterThanOrEqualTo(e){return typeof e=="string"&&(e=Tt.getLevel(e)),this.level>=e.level}isEqualTo(e){return typeof e=="string"&&(e=Tt.getLevel(e)),this.level===e.level}};Tt.levels=[];Tt.addLevels({ALL:{value:Number.MIN_VALUE,colour:"grey"},TRACE:{value:5e3,colour:"blue"},DEBUG:{value:1e4,colour:"cyan"},INFO:{value:2e4,colour:"green"},WARN:{value:3e4,colour:"yellow"},ERROR:{value:4e4,colour:"red"},FATAL:{value:5e4,colour:"magenta"},MARK:{value:9007199254740992,colour:"grey"},OFF:{value:Number.MAX_VALUE,colour:"grey"}});vt.addListener(r=>{let e=r.levels;e&&(vt.throwExceptionIf(r,vt.not(vt.anObject(e)),"levels must be an object"),Object.keys(e).forEach(i=>{vt.throwExceptionIf(r,vt.not(vt.validIdentifier(i)),`level name "${i}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)`),vt.throwExceptionIf(r,vt.not(vt.anObject(e[i])),`level "${i}" must be an object`),vt.throwExceptionIf(r,vt.not(e[i].value),`level "${i}" must have a 'value' property`),vt.throwExceptionIf(r,vt.not(vt.anInteger(e[i].value)),`level "${i}".value must have an integer value`),vt.throwExceptionIf(r,vt.not(e[i].colour),`level "${i}" must have a 'colour' property`),vt.throwExceptionIf(r,vt.not(vR.indexOf(e[i].colour)>-1),`level "${i}".colour must be one of ${vR.join(", ")}`)}))});vt.addListener(r=>{Tt.addLevels(r.levels)});gR.exports=Tt});var yR=g(iX=>{fo(iX,{default:()=>nX,parse:()=>oX,stringify:()=>sX});var tb=function(r,e){var t={parse:function(u,c){var f=JSON.parse(u,a).map(s),p=f[0],d=c||i,h=typeof p=="object"&&p?n(f,new Set,p,d):p;return d.call({"":h},"",h)},stringify:function(u,c,f){for(var p,d=new Map,h=[],m=[],y=c&&typeof c==typeof h?function(w,E){if(w===""||-1{var wR=yR(),xR=Ds(),nc=class{constructor(e,t,i,n,o){this.startTime=new Date,this.categoryName=e,this.data=i,this.level=t,this.context=Object.assign({},n),this.pid=process.pid,o&&(this.functionName=o.functionName,this.fileName=o.fileName,this.lineNumber=o.lineNumber,this.columnNumber=o.columnNumber,this.callStack=o.callStack)}serialise(){let e=this.data.map(t=>(t&&t.message&&t.stack&&(t=Object.assign({message:t.message,stack:t.stack},t)),t));return this.data=e,wR.stringify(this)}static deserialise(e){let t;try{let i=wR.parse(e);i.data=i.data.map(n=>{if(n&&n.message&&n.stack){let o=new Error(n);Object.keys(n).forEach(s=>{o[s]=n[s]}),n=o}return n}),t=new nc(i.categoryName,xR.getLevel(i.level.levelStr),i.data,i.context),t.startTime=new Date(i.startTime),t.pid=i.pid,t.cluster=i.cluster}catch(i){t=new nc("log4js",xR.ERROR,["Unable to parse log:",e,"because: ",i])}return t}};bR.exports=nc});var Ld=g((USe,DR)=>{var ci=gt()("log4js:clustering"),aX=rb(),lX=bs(),$a=!1,cn=null;try{cn=require("cluster")}catch(r){ci("cluster module not present"),$a=!0}var ib=[],oc=!1,sc="NODE_APP_INSTANCE",SR=()=>oc&&process.env[sc]==="0",nb=()=>$a||cn.isMaster||SR(),ER=r=>{ib.forEach(e=>e(r))},Od=(r,e)=>{if(ci("cluster message received from worker ",r,": ",e),r.topic&&r.data&&(e=r,r=void 0),e&&e.topic&&e.topic==="log4js:message"){ci("received message: ",e.data);let t=aX.deserialise(e.data);ER(t)}};$a||lX.addListener(r=>{ib.length=0,{pm2:oc,disableClustering:$a,pm2InstanceVar:sc="NODE_APP_INSTANCE"}=r,ci(`clustering disabled ? ${$a}`),ci(`cluster.isMaster ? ${cn&&cn.isMaster}`),ci(`pm2 enabled ? ${oc}`),ci(`pm2InstanceVar = ${sc}`),ci(`process.env[${sc}] = ${process.env[sc]}`),oc&&process.removeListener("message",Od),cn&&cn.removeListener&&cn.removeListener("message",Od),$a||r.disableClustering?ci("Not listening for cluster messages, because clustering disabled."):SR()?(ci("listening for PM2 broadcast messages"),process.on("message",Od)):cn.isMaster?(ci("listening for cluster messages"),cn.on("message",Od)):ci("not listening for messages, because we are not a master process")});DR.exports={onlyOnMaster:(r,e)=>nb()?r():e,isMaster:nb,send:r=>{nb()?ER(r):(oc||(r.cluster={workerId:cn.worker.id,worker:process.pid}),process.send({topic:"log4js:message",data:r.serialise()}))},onMessage:r=>{ib.push(r)}}});var TR=g((WSe,CR)=>{function uX(r){if(typeof r=="number"&&Number.isInteger(r))return r;let e={K:1024,M:1024*1024,G:1024*1024*1024},t=Object.keys(e),i=r.substr(r.length-1).toLocaleUpperCase(),n=r.substring(0,r.length-1).trim();if(t.indexOf(i)<0||!Number.isInteger(Number(n)))throw Error(`maxLogSize: "${r}" is invalid`);return n*e[i]}function cX(r,e){let t=Object.assign({},e);return Object.keys(r).forEach(i=>{t[i]&&(t[i]=r[i](e[i]))}),t}function _R(r){return cX({maxLogSize:uX},r)}var PR={file:_R,fileSync:_R};CR.exports.modifyConfig=r=>PR[r.type]?PR[r.type](r):r});var kR=g((HSe,RR)=>{var fX=console.log.bind(console);function pX(r,e){return t=>{fX(r(t,e))}}function dX(r,e){let t=e.colouredLayout;return r.layout&&(t=e.layout(r.layout.type,r.layout)),pX(t,r.timezoneOffset)}RR.exports.configure=dX});var FR=g(IR=>{function hX(r,e){return t=>{process.stdout.write(`${r(t,e)} +`)}}function mX(r,e){let t=e.colouredLayout;return r.layout&&(t=e.layout(r.layout.type,r.layout)),hX(t,r.timezoneOffset)}IR.configure=mX});var OR=g((GSe,AR)=>{function gX(r,e){return t=>{process.stderr.write(`${r(t,e)} +`)}}function vX(r,e){let t=e.colouredLayout;return r.layout&&(t=e.layout(r.layout.type,r.layout)),gX(t,r.timezoneOffset)}AR.exports.configure=vX});var MR=g((VSe,LR)=>{function yX(r,e,t,i){let n=i.getLevel(r),o=i.getLevel(e,i.FATAL);return s=>{let a=s.level;a.isGreaterThanOrEqualTo(n)&&a.isLessThanOrEqualTo(o)&&t(s)}}function bX(r,e,t,i){let n=t(r.appender);return yX(r.level,r.maxLevel,n,i)}LR.exports.configure=bX});var $R=g((KSe,NR)=>{var qR=gt()("log4js:categoryFilter");function wX(r,e){return typeof r=="string"&&(r=[r]),t=>{qR(`Checking ${t.categoryName} against ${r}`),r.indexOf(t.categoryName)===-1&&(qR("Not excluded, sending to appender"),e(t))}}function xX(r,e,t){let i=t(r.appender);return wX(r.exclude,i)}NR.exports.configure=xX});var UR=g((JSe,BR)=>{var jR=gt()("log4js:noLogFilter");function DX(r){return r.filter(t=>t!=null&&t!=="")}function SX(r,e){return t=>{jR(`Checking data: ${t.data} against filters: ${r}`),typeof r=="string"&&(r=[r]),r=DX(r);let i=new RegExp(r.join("|"),"i");(r.length===0||t.data.findIndex(n=>i.test(n))<0)&&(jR("Not excluded, sending to appender"),e(t))}}function EX(r,e,t){let i=t(r.appender);return SX(r.exclude,i)}BR.exports.configure=EX});var Er=g(ob=>{"use strict";ob.fromCallback=function(r){return Object.defineProperty(function(){if(typeof arguments[arguments.length-1]=="function")r.apply(this,arguments);else return new Promise((e,t)=>{arguments[arguments.length]=(i,n)=>{if(i)return t(i);e(n)},arguments.length++,r.apply(this,arguments)})},"name",{value:r.name})};ob.fromPromise=function(r){return Object.defineProperty(function(){let e=arguments[arguments.length-1];if(typeof e!="function")return r.apply(this,arguments);r.apply(this,arguments).then(t=>e(null,t),e)},"name",{value:r.name})}});var HR=g((XSe,WR)=>{var go=require("constants"),CX=process.cwd,Md=null,_X=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Md||(Md=CX.call(process)),Md};try{process.cwd()}catch(r){}var PX=process.chdir;process.chdir=function(r){Md=null,PX.call(process,r)};WR.exports=TX;function TX(r){go.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&e(r),r.lutimes||t(r),r.chown=o(r.chown),r.fchown=o(r.fchown),r.lchown=o(r.lchown),r.chmod=i(r.chmod),r.fchmod=i(r.fchmod),r.lchmod=i(r.lchmod),r.chownSync=s(r.chownSync),r.fchownSync=s(r.fchownSync),r.lchownSync=s(r.lchownSync),r.chmodSync=n(r.chmodSync),r.fchmodSync=n(r.fchmodSync),r.lchmodSync=n(r.lchmodSync),r.stat=a(r.stat),r.fstat=a(r.fstat),r.lstat=a(r.lstat),r.statSync=l(r.statSync),r.fstatSync=l(r.fstatSync),r.lstatSync=l(r.lstatSync),r.lchmod||(r.lchmod=function(c,f,p){p&&process.nextTick(p)},r.lchmodSync=function(){}),r.lchown||(r.lchown=function(c,f,p,d){d&&process.nextTick(d)},r.lchownSync=function(){}),_X==="win32"&&(r.rename=function(c){return function(f,p,d){var h=Date.now(),m=0;c(f,p,function y(v){if(v&&(v.code==="EACCES"||v.code==="EPERM")&&Date.now()-h<6e4){setTimeout(function(){r.stat(p,function(x,w){x&&x.code==="ENOENT"?c(f,p,y):d(v)})},m),m<100&&(m+=10);return}d&&d(v)})}}(r.rename)),r.read=function(c){function f(p,d,h,m,y,v){var x;if(v&&typeof v=="function"){var w=0;x=function(E,P,k){if(E&&E.code==="EAGAIN"&&w<10)return w++,c.call(r,p,d,h,m,y,x);v.apply(this,arguments)}}return c.call(r,p,d,h,m,y,x)}return f.__proto__=c,f}(r.read),r.readSync=function(c){return function(f,p,d,h,m){for(var y=0;;)try{return c.call(r,f,p,d,h,m)}catch(v){if(v.code==="EAGAIN"&&y<10){y++;continue}throw v}}}(r.readSync);function e(c){c.lchmod=function(f,p,d){c.open(f,go.O_WRONLY|go.O_SYMLINK,p,function(h,m){if(h){d&&d(h);return}c.fchmod(m,p,function(y){c.close(m,function(v){d&&d(y||v)})})})},c.lchmodSync=function(f,p){var d=c.openSync(f,go.O_WRONLY|go.O_SYMLINK,p),h=!0,m;try{m=c.fchmodSync(d,p),h=!1}finally{if(h)try{c.closeSync(d)}catch(y){}else c.closeSync(d)}return m}}function t(c){go.hasOwnProperty("O_SYMLINK")?(c.lutimes=function(f,p,d,h){c.open(f,go.O_SYMLINK,function(m,y){if(m){h&&h(m);return}c.futimes(y,p,d,function(v){c.close(y,function(x){h&&h(v||x)})})})},c.lutimesSync=function(f,p,d){var h=c.openSync(f,go.O_SYMLINK),m,y=!0;try{m=c.futimesSync(h,p,d),y=!1}finally{if(y)try{c.closeSync(h)}catch(v){}else c.closeSync(h)}return m}):(c.lutimes=function(f,p,d,h){h&&process.nextTick(h)},c.lutimesSync=function(){})}function i(c){return c&&function(f,p,d){return c.call(r,f,p,function(h){u(h)&&(h=null),d&&d.apply(this,arguments)})}}function n(c){return c&&function(f,p){try{return c.call(r,f,p)}catch(d){if(!u(d))throw d}}}function o(c){return c&&function(f,p,d,h){return c.call(r,f,p,d,function(m){u(m)&&(m=null),h&&h.apply(this,arguments)})}}function s(c){return c&&function(f,p,d){try{return c.call(r,f,p,d)}catch(h){if(!u(h))throw h}}}function a(c){return c&&function(f,p,d){typeof p=="function"&&(d=p,p=null);function h(m,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),d&&d.apply(this,arguments)}return p?c.call(r,f,p,h):c.call(r,f,h)}}function l(c){return c&&function(f,p){var d=p?c.call(r,f,p):c.call(r,f);return d.uid<0&&(d.uid+=4294967296),d.gid<0&&(d.gid+=4294967296),d}}function u(c){if(!c||c.code==="ENOSYS")return!0;var f=!process.getuid||process.getuid()!==0;return!!(f&&(c.code==="EINVAL"||c.code==="EPERM"))}}});var VR=g((ZSe,zR)=>{var GR=require("stream").Stream;zR.exports=RX;function RX(r){return{ReadStream:e,WriteStream:t};function e(i,n){if(!(this instanceof e))return new e(i,n);GR.call(this);var o=this;this.path=i,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,n=n||{};for(var s=Object.keys(n),a=0,l=s.length;athis.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){o._read()});return}r.open(this.path,this.flags,this.mode,function(c,f){if(c){o.emit("error",c),o.readable=!1;return}o.fd=f,o.emit("open",f),o._read()})}function t(i,n){if(!(this instanceof t))return new t(i,n);GR.call(this),this.path=i,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,n=n||{};for(var o=Object.keys(n),s=0,a=o.length;s= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=r.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var JR=g((QSe,KR)=>{"use strict";KR.exports=kX;function kX(r){if(r===null||typeof r!="object")return r;if(r instanceof Object)var e={__proto__:r.__proto__};else var e=Object.create(null);return Object.getOwnPropertyNames(r).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}),e}});var Ce=g((eEe,sb)=>{var $t=require("fs"),IX=HR(),FX=VR(),AX=JR(),Nd=require("util"),Ni,qd;typeof Symbol=="function"&&typeof Symbol.for=="function"?(Ni=Symbol.for("graceful-fs.queue"),qd=Symbol.for("graceful-fs.previous")):(Ni="___graceful-fs.queue",qd="___graceful-fs.previous");function OX(){}function YR(r,e){Object.defineProperty(r,Ni,{get:function(){return e}})}var ac=OX;Nd.debuglog?ac=Nd.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(ac=function(){var r=Nd.format.apply(Nd,arguments);r="GFS4: "+r.split(/\n/).join(` +GFS4: `),console.error(r)});$t[Ni]||(XR=global[Ni]||[],YR($t,XR),$t.close=function(r){function e(t,i){return r.call($t,t,function(n){n||Ss(),typeof i=="function"&&i.apply(this,arguments)})}return Object.defineProperty(e,qd,{value:r}),e}($t.close),$t.closeSync=function(r){function e(t){r.apply($t,arguments),Ss()}return Object.defineProperty(e,qd,{value:r}),e}($t.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){ac($t[Ni]),require("assert").equal($t[Ni].length,0)}));var XR;global[Ni]||YR(global,$t[Ni]);sb.exports=ab(AX($t));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!$t.__patched&&(sb.exports=ab($t),$t.__patched=!0);function ab(r){IX(r),r.gracefulify=ab,r.createReadStream=w,r.createWriteStream=E;var e=r.readFile;r.readFile=t;function t(_,O,I){return typeof O=="function"&&(I=O,O=null),L(_,O,I);function L(R,F,q){return e(R,F,function(K){K&&(K.code==="EMFILE"||K.code==="ENFILE")?lc([L,[R,F,q]]):(typeof q=="function"&&q.apply(this,arguments),Ss())})}}var i=r.writeFile;r.writeFile=n;function n(_,O,I,L){return typeof I=="function"&&(L=I,I=null),R(_,O,I,L);function R(F,q,K,ae){return i(F,q,K,function(Pe){Pe&&(Pe.code==="EMFILE"||Pe.code==="ENFILE")?lc([R,[F,q,K,ae]]):(typeof ae=="function"&&ae.apply(this,arguments),Ss())})}}var o=r.appendFile;o&&(r.appendFile=s);function s(_,O,I,L){return typeof I=="function"&&(L=I,I=null),R(_,O,I,L);function R(F,q,K,ae){return o(F,q,K,function(Pe){Pe&&(Pe.code==="EMFILE"||Pe.code==="ENFILE")?lc([R,[F,q,K,ae]]):(typeof ae=="function"&&ae.apply(this,arguments),Ss())})}}var a=r.readdir;r.readdir=l;function l(_,O,I){var L=[_];return typeof O!="function"?L.push(O):I=O,L.push(R),u(L);function R(F,q){q&&q.sort&&q.sort(),F&&(F.code==="EMFILE"||F.code==="ENFILE")?lc([u,[L]]):(typeof I=="function"&&I.apply(this,arguments),Ss())}}function u(_){return a.apply(r,_)}if(process.version.substr(0,4)==="v0.8"){var c=FX(r);m=c.ReadStream,v=c.WriteStream}var f=r.ReadStream;f&&(m.prototype=Object.create(f.prototype),m.prototype.open=y);var p=r.WriteStream;p&&(v.prototype=Object.create(p.prototype),v.prototype.open=x),Object.defineProperty(r,"ReadStream",{get:function(){return m},set:function(_){m=_},enumerable:!0,configurable:!0}),Object.defineProperty(r,"WriteStream",{get:function(){return v},set:function(_){v=_},enumerable:!0,configurable:!0});var d=m;Object.defineProperty(r,"FileReadStream",{get:function(){return d},set:function(_){d=_},enumerable:!0,configurable:!0});var h=v;Object.defineProperty(r,"FileWriteStream",{get:function(){return h},set:function(_){h=_},enumerable:!0,configurable:!0});function m(_,O){return this instanceof m?(f.apply(this,arguments),this):m.apply(Object.create(m.prototype),arguments)}function y(){var _=this;k(_.path,_.flags,_.mode,function(O,I){O?(_.autoClose&&_.destroy(),_.emit("error",O)):(_.fd=I,_.emit("open",I),_.read())})}function v(_,O){return this instanceof v?(p.apply(this,arguments),this):v.apply(Object.create(v.prototype),arguments)}function x(){var _=this;k(_.path,_.flags,_.mode,function(O,I){O?(_.destroy(),_.emit("error",O)):(_.fd=I,_.emit("open",I))})}function w(_,O){return new r.ReadStream(_,O)}function E(_,O){return new r.WriteStream(_,O)}var P=r.open;r.open=k;function k(_,O,I,L){return typeof I=="function"&&(L=I,I=null),R(_,O,I,L);function R(F,q,K,ae){return P(F,q,K,function(Pe,We){Pe&&(Pe.code==="EMFILE"||Pe.code==="ENFILE")?lc([R,[F,q,K,ae]]):(typeof ae=="function"&&ae.apply(this,arguments),Ss())})}}return r}function lc(r){ac("ENQUEUE",r[0].name,r[1]),$t[Ni].push(r)}function Ss(){var r=$t[Ni].shift();r&&(ac("RETRY",r[0].name,r[1]),r[0].apply(null,r[1]))}});var lb=g(Es=>{"use strict";var ZR=Er().fromCallback,fi=Ce(),LX=["access","appendFile","chmod","chown","close","copyFile","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","lchown","lchmod","link","lstat","mkdir","mkdtemp","open","readFile","readdir","readlink","realpath","rename","rmdir","stat","symlink","truncate","unlink","utimes","writeFile"].filter(r=>typeof fi[r]=="function");Object.keys(fi).forEach(r=>{r!=="promises"&&(Es[r]=fi[r])});LX.forEach(r=>{Es[r]=ZR(fi[r])});Es.exists=function(r,e){return typeof e=="function"?fi.exists(r,e):new Promise(t=>fi.exists(r,t))};Es.read=function(r,e,t,i,n,o){return typeof o=="function"?fi.read(r,e,t,i,n,o):new Promise((s,a)=>{fi.read(r,e,t,i,n,(l,u,c)=>{if(l)return a(l);s({bytesRead:u,buffer:c})})})};Es.write=function(r,e,...t){return typeof t[t.length-1]=="function"?fi.write(r,e,...t):new Promise((i,n)=>{fi.write(r,e,...t,(o,s,a)=>{if(o)return n(o);i({bytesWritten:s,buffer:a})})})};typeof fi.realpath.native=="function"&&(Es.realpath.native=ZR(fi.realpath.native))});var cb=g((rEe,QR)=>{"use strict";var ub=require("path");function e1(r){return r=ub.normalize(ub.resolve(r)).split(ub.sep),r.length>0?r[0]:null}var MX=/[<>:"|?*]/;function NX(r){let e=e1(r);return r=r.replace(e,""),MX.test(r)}QR.exports={getRootPath:e1,invalidWin32Path:NX}});var r1=g((iEe,t1)=>{"use strict";var qX=Ce(),fb=require("path"),$X=cb().invalidWin32Path,BX=parseInt("0777",8);function pb(r,e,t,i){if(typeof e=="function"?(t=e,e={}):(!e||typeof e!="object")&&(e={mode:e}),process.platform==="win32"&&$X(r)){let s=new Error(r+" contains invalid WIN32 path characters.");return s.code="EINVAL",t(s)}let n=e.mode,o=e.fs||qX;n===void 0&&(n=BX&~process.umask()),i||(i=null),t=t||function(){},r=fb.resolve(r),o.mkdir(r,n,s=>{if(!s)return i=i||r,t(null,i);switch(s.code){case"ENOENT":if(fb.dirname(r)===r)return t(s);pb(fb.dirname(r),e,(a,l)=>{a?t(a,l):pb(r,e,t,l)});break;default:o.stat(r,(a,l)=>{a||!l.isDirectory()?t(s,i):t(null,i)});break}})}t1.exports=pb});var n1=g((nEe,i1)=>{"use strict";var jX=Ce(),db=require("path"),UX=cb().invalidWin32Path,WX=parseInt("0777",8);function hb(r,e,t){(!e||typeof e!="object")&&(e={mode:e});let i=e.mode,n=e.fs||jX;if(process.platform==="win32"&&UX(r)){let o=new Error(r+" contains invalid WIN32 path characters.");throw o.code="EINVAL",o}i===void 0&&(i=WX&~process.umask()),t||(t=null),r=db.resolve(r);try{n.mkdirSync(r,i),t=t||r}catch(o){if(o.code==="ENOENT"){if(db.dirname(r)===r)throw o;t=hb(db.dirname(r),e,t),hb(r,e,t)}else{let s;try{s=n.statSync(r)}catch(a){throw o}if(!s.isDirectory())throw o}}return t}i1.exports=hb});var Br=g((oEe,o1)=>{"use strict";var HX=Er().fromCallback,mb=HX(r1()),gb=n1();o1.exports={mkdirs:mb,mkdirsSync:gb,mkdirp:mb,mkdirpSync:gb,ensureDir:mb,ensureDirSync:gb}});var vb=g((sEe,s1)=>{"use strict";var er=Ce(),a1=require("os"),$d=require("path");function zX(){let r=$d.join("millis-test-sync"+Date.now().toString()+Math.random().toString().slice(2));r=$d.join(a1.tmpdir(),r);let e=new Date(1435410243862);er.writeFileSync(r,"https://github.com/jprichardson/node-fs-extra/pull/141");let t=er.openSync(r,"r+");return er.futimesSync(t,e,e),er.closeSync(t),er.statSync(r).mtime>1435410243e3}function GX(r){let e=$d.join("millis-test"+Date.now().toString()+Math.random().toString().slice(2));e=$d.join(a1.tmpdir(),e);let t=new Date(1435410243862);er.writeFile(e,"https://github.com/jprichardson/node-fs-extra/pull/141",i=>{if(i)return r(i);er.open(e,"r+",(n,o)=>{if(n)return r(n);er.futimes(o,t,t,s=>{if(s)return r(s);er.close(o,a=>{if(a)return r(a);er.stat(e,(l,u)=>{if(l)return r(l);r(null,u.mtime>1435410243e3)})})})})})}function VX(r){if(typeof r=="number")return Math.floor(r/1e3)*1e3;if(r instanceof Date)return new Date(Math.floor(r.getTime()/1e3)*1e3);throw new Error("fs-extra: timeRemoveMillis() unknown parameter type")}function KX(r,e,t,i){er.open(r,"r+",(n,o)=>{if(n)return i(n);er.futimes(o,e,t,s=>{er.close(o,a=>{i&&i(s||a)})})})}function JX(r,e,t){let i=er.openSync(r,"r+");return er.futimesSync(i,e,t),er.closeSync(i)}s1.exports={hasMillisRes:GX,hasMillisResSync:zX,timeRemoveMillis:VX,utimesMillis:KX,utimesMillisSync:JX}});var fc=g((aEe,l1)=>{"use strict";var pi=Ce(),Cr=require("path"),u1=10,c1=5,YX=0,yb=process.versions.node.split("."),f1=Number.parseInt(yb[0],10),p1=Number.parseInt(yb[1],10),XX=Number.parseInt(yb[2],10);function uc(){if(f1>u1)return!0;if(f1===u1){if(p1>c1)return!0;if(p1===c1&&XX>=YX)return!0}return!1}function ZX(r,e,t){uc()?pi.stat(r,{bigint:!0},(i,n)=>{if(i)return t(i);pi.stat(e,{bigint:!0},(o,s)=>o?o.code==="ENOENT"?t(null,{srcStat:n,destStat:null}):t(o):t(null,{srcStat:n,destStat:s}))}):pi.stat(r,(i,n)=>{if(i)return t(i);pi.stat(e,(o,s)=>o?o.code==="ENOENT"?t(null,{srcStat:n,destStat:null}):t(o):t(null,{srcStat:n,destStat:s}))})}function QX(r,e){let t,i;uc()?t=pi.statSync(r,{bigint:!0}):t=pi.statSync(r);try{uc()?i=pi.statSync(e,{bigint:!0}):i=pi.statSync(e)}catch(n){if(n.code==="ENOENT")return{srcStat:t,destStat:null};throw n}return{srcStat:t,destStat:i}}function eZ(r,e,t,i){ZX(r,e,(n,o)=>{if(n)return i(n);let{srcStat:s,destStat:a}=o;return a&&a.ino&&a.dev&&a.ino===s.ino&&a.dev===s.dev?i(new Error("Source and destination must not be the same.")):s.isDirectory()&&bb(r,e)?i(new Error(cc(r,e,t))):i(null,{srcStat:s,destStat:a})})}function tZ(r,e,t){let{srcStat:i,destStat:n}=QX(r,e);if(n&&n.ino&&n.dev&&n.ino===i.ino&&n.dev===i.dev)throw new Error("Source and destination must not be the same.");if(i.isDirectory()&&bb(r,e))throw new Error(cc(r,e,t));return{srcStat:i,destStat:n}}function wb(r,e,t,i,n){let o=Cr.resolve(Cr.dirname(r)),s=Cr.resolve(Cr.dirname(t));if(s===o||s===Cr.parse(s).root)return n();uc()?pi.stat(s,{bigint:!0},(a,l)=>a?a.code==="ENOENT"?n():n(a):l.ino&&l.dev&&l.ino===e.ino&&l.dev===e.dev?n(new Error(cc(r,t,i))):wb(r,e,s,i,n)):pi.stat(s,(a,l)=>a?a.code==="ENOENT"?n():n(a):l.ino&&l.dev&&l.ino===e.ino&&l.dev===e.dev?n(new Error(cc(r,t,i))):wb(r,e,s,i,n))}function d1(r,e,t,i){let n=Cr.resolve(Cr.dirname(r)),o=Cr.resolve(Cr.dirname(t));if(o===n||o===Cr.parse(o).root)return;let s;try{uc()?s=pi.statSync(o,{bigint:!0}):s=pi.statSync(o)}catch(a){if(a.code==="ENOENT")return;throw a}if(s.ino&&s.dev&&s.ino===e.ino&&s.dev===e.dev)throw new Error(cc(r,t,i));return d1(r,e,o,i)}function bb(r,e){let t=Cr.resolve(r).split(Cr.sep).filter(n=>n),i=Cr.resolve(e).split(Cr.sep).filter(n=>n);return t.reduce((n,o,s)=>n&&i[s]===o,!0)}function cc(r,e,t){return`Cannot ${t} '${r}' to a subdirectory of itself, '${e}'.`}l1.exports={checkPaths:eZ,checkPathsSync:tZ,checkParentPaths:wb,checkParentPathsSync:d1,isSrcSubdir:bb}});var m1=g((lEe,h1)=>{"use strict";h1.exports=function(r){if(typeof Buffer.allocUnsafe=="function")try{return Buffer.allocUnsafe(r)}catch(e){return new Buffer(r)}return new Buffer(r)}});var w1=g((uEe,g1)=>{"use strict";var it=Ce(),pc=require("path"),rZ=Br().mkdirsSync,iZ=vb().utimesMillisSync,dc=fc();function oZ(r,e,t){typeof t=="function"&&(t={filter:t}),t=t||{},t.clobber="clobber"in t?!!t.clobber:!0,t.overwrite="overwrite"in t?!!t.overwrite:t.clobber,t.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`);let{srcStat:i,destStat:n}=dc.checkPathsSync(r,e,"copy");return dc.checkParentPathsSync(r,i,e,"copy"),nZ(n,r,e,t)}function nZ(r,e,t,i){if(i.filter&&!i.filter(e,t))return;let n=pc.dirname(t);return it.existsSync(n)||rZ(n),v1(r,e,t,i)}function v1(r,e,t,i){if(!(i.filter&&!i.filter(e,t)))return sZ(r,e,t,i)}function sZ(r,e,t,i){let o=(i.dereference?it.statSync:it.lstatSync)(e);if(o.isDirectory())return lZ(o,r,e,t,i);if(o.isFile()||o.isCharacterDevice()||o.isBlockDevice())return aZ(o,r,e,t,i);if(o.isSymbolicLink())return uZ(r,e,t,i)}function aZ(r,e,t,i,n){return e?cZ(r,t,i,n):y1(r,t,i,n)}function cZ(r,e,t,i){if(i.overwrite)return it.unlinkSync(t),y1(r,e,t,i);if(i.errorOnExist)throw new Error(`'${t}' already exists`)}function y1(r,e,t,i){return typeof it.copyFileSync=="function"?(it.copyFileSync(e,t),it.chmodSync(t,r.mode),i.preserveTimestamps?iZ(t,r.atime,r.mtime):void 0):fZ(r,e,t,i)}function fZ(r,e,t,i){let n=64*1024,o=m1()(n),s=it.openSync(e,"r"),a=it.openSync(t,"w",r.mode),l=0;for(;ldZ(i,r,e,t))}function dZ(r,e,t,i){let n=pc.join(e,r),o=pc.join(t,r),{destStat:s}=dc.checkPathsSync(n,o,"copy");return v1(s,n,o,i)}function uZ(r,e,t,i){let n=it.readlinkSync(e);if(i.dereference&&(n=pc.resolve(process.cwd(),n)),r){let o;try{o=it.readlinkSync(t)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return it.symlinkSync(n,t);throw s}if(i.dereference&&(o=pc.resolve(process.cwd(),o)),dc.isSrcSubdir(n,o))throw new Error(`Cannot copy '${n}' to a subdirectory of itself, '${o}'.`);if(it.statSync(t).isDirectory()&&dc.isSrcSubdir(o,n))throw new Error(`Cannot overwrite '${o}' with '${n}'.`);return hZ(n,t)}else return it.symlinkSync(n,t)}function hZ(r,e){return it.unlinkSync(e),it.symlinkSync(r,e)}g1.exports=oZ});var xb=g((cEe,x1)=>{"use strict";x1.exports={copySync:w1()}});var fn=g((fEe,D1)=>{"use strict";var mZ=Er().fromPromise,S1=lb();function gZ(r){return S1.access(r).then(()=>!0).catch(()=>!1)}D1.exports={pathExists:mZ(gZ),pathExistsSync:S1.existsSync}});var F1=g((pEe,E1)=>{"use strict";var Bt=Ce(),hc=require("path"),vZ=Br().mkdirs,yZ=fn().pathExists,bZ=vb().utimesMillis,mc=fc();function wZ(r,e,t,i){typeof t=="function"&&!i?(i=t,t={}):typeof t=="function"&&(t={filter:t}),i=i||function(){},t=t||{},t.clobber="clobber"in t?!!t.clobber:!0,t.overwrite="overwrite"in t?!!t.overwrite:t.clobber,t.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`),mc.checkPaths(r,e,"copy",(n,o)=>{if(n)return i(n);let{srcStat:s,destStat:a}=o;mc.checkParentPaths(r,s,e,"copy",l=>l?i(l):t.filter?_1(C1,a,r,e,t,i):C1(a,r,e,t,i))})}function C1(r,e,t,i,n){let o=hc.dirname(t);yZ(o,(s,a)=>{if(s)return n(s);if(a)return Db(r,e,t,i,n);vZ(o,l=>l?n(l):Db(r,e,t,i,n))})}function _1(r,e,t,i,n,o){Promise.resolve(n.filter(t,i)).then(s=>s?r(e,t,i,n,o):o(),s=>o(s))}function Db(r,e,t,i,n){return i.filter?_1(P1,r,e,t,i,n):P1(r,e,t,i,n)}function P1(r,e,t,i,n){(i.dereference?Bt.stat:Bt.lstat)(e,(s,a)=>{if(s)return n(s);if(a.isDirectory())return DZ(a,r,e,t,i,n);if(a.isFile()||a.isCharacterDevice()||a.isBlockDevice())return xZ(a,r,e,t,i,n);if(a.isSymbolicLink())return SZ(r,e,t,i,n)})}function xZ(r,e,t,i,n,o){return e?EZ(r,t,i,n,o):T1(r,t,i,n,o)}function EZ(r,e,t,i,n){if(i.overwrite)Bt.unlink(t,o=>o?n(o):T1(r,e,t,i,n));else return i.errorOnExist?n(new Error(`'${t}' already exists`)):n()}function T1(r,e,t,i,n){return typeof Bt.copyFile=="function"?Bt.copyFile(e,t,o=>o?n(o):R1(r,t,i,n)):CZ(r,e,t,i,n)}function CZ(r,e,t,i,n){let o=Bt.createReadStream(e);o.on("error",s=>n(s)).once("open",()=>{let s=Bt.createWriteStream(t,{mode:r.mode});s.on("error",a=>n(a)).on("open",()=>o.pipe(s)).once("close",()=>R1(r,t,i,n))})}function R1(r,e,t,i){Bt.chmod(e,r.mode,n=>n?i(n):t.preserveTimestamps?bZ(e,r.atime,r.mtime,i):i())}function DZ(r,e,t,i,n,o){return e?e&&!e.isDirectory()?o(new Error(`Cannot overwrite non-directory '${i}' with directory '${t}'.`)):k1(t,i,n,o):_Z(r,t,i,n,o)}function _Z(r,e,t,i,n){Bt.mkdir(t,o=>{if(o)return n(o);k1(e,t,i,s=>s?n(s):Bt.chmod(t,r.mode,n))})}function k1(r,e,t,i){Bt.readdir(r,(n,o)=>n?i(n):I1(o,r,e,t,i))}function I1(r,e,t,i,n){let o=r.pop();return o?PZ(r,o,e,t,i,n):n()}function PZ(r,e,t,i,n,o){let s=hc.join(t,e),a=hc.join(i,e);mc.checkPaths(s,a,"copy",(l,u)=>{if(l)return o(l);let{destStat:c}=u;Db(c,s,a,n,f=>f?o(f):I1(r,t,i,n,o))})}function SZ(r,e,t,i,n){Bt.readlink(e,(o,s)=>{if(o)return n(o);if(i.dereference&&(s=hc.resolve(process.cwd(),s)),r)Bt.readlink(t,(a,l)=>a?a.code==="EINVAL"||a.code==="UNKNOWN"?Bt.symlink(s,t,n):n(a):(i.dereference&&(l=hc.resolve(process.cwd(),l)),mc.isSrcSubdir(s,l)?n(new Error(`Cannot copy '${s}' to a subdirectory of itself, '${l}'.`)):r.isDirectory()&&mc.isSrcSubdir(l,s)?n(new Error(`Cannot overwrite '${l}' with '${s}'.`)):TZ(s,t,n)));else return Bt.symlink(s,t,n)})}function TZ(r,e,t){Bt.unlink(e,i=>i?t(i):Bt.symlink(r,e,t))}E1.exports=wZ});var Sb=g((dEe,A1)=>{"use strict";var RZ=Er().fromCallback;A1.exports={copy:RZ(F1())}});var U1=g((hEe,O1)=>{"use strict";var L1=Ce(),M1=require("path"),Oe=require("assert"),gc=process.platform==="win32";function N1(r){["unlink","chmod","stat","lstat","rmdir","readdir"].forEach(t=>{r[t]=r[t]||L1[t],t=t+"Sync",r[t]=r[t]||L1[t]}),r.maxBusyTries=r.maxBusyTries||3}function Eb(r,e,t){let i=0;typeof e=="function"&&(t=e,e={}),Oe(r,"rimraf: missing path"),Oe.strictEqual(typeof r,"string","rimraf: path should be a string"),Oe.strictEqual(typeof t,"function","rimraf: callback function required"),Oe(e,"rimraf: invalid options argument provided"),Oe.strictEqual(typeof e,"object","rimraf: options should be object"),N1(e),q1(r,e,function n(o){if(o){if((o.code==="EBUSY"||o.code==="ENOTEMPTY"||o.code==="EPERM")&&iq1(r,e,n),s)}o.code==="ENOENT"&&(o=null)}t(o)})}function q1(r,e,t){Oe(r),Oe(e),Oe(typeof t=="function"),e.lstat(r,(i,n)=>{if(i&&i.code==="ENOENT")return t(null);if(i&&i.code==="EPERM"&&gc)return $1(r,e,i,t);if(n&&n.isDirectory())return Bd(r,e,i,t);e.unlink(r,o=>{if(o){if(o.code==="ENOENT")return t(null);if(o.code==="EPERM")return gc?$1(r,e,o,t):Bd(r,e,o,t);if(o.code==="EISDIR")return Bd(r,e,o,t)}return t(o)})})}function $1(r,e,t,i){Oe(r),Oe(e),Oe(typeof i=="function"),t&&Oe(t instanceof Error),e.chmod(r,438,n=>{n?i(n.code==="ENOENT"?null:t):e.stat(r,(o,s)=>{o?i(o.code==="ENOENT"?null:t):s.isDirectory()?Bd(r,e,t,i):e.unlink(r,i)})})}function B1(r,e,t){let i;Oe(r),Oe(e),t&&Oe(t instanceof Error);try{e.chmodSync(r,438)}catch(n){if(n.code==="ENOENT")return;throw t}try{i=e.statSync(r)}catch(n){if(n.code==="ENOENT")return;throw t}i.isDirectory()?jd(r,e,t):e.unlinkSync(r)}function Bd(r,e,t,i){Oe(r),Oe(e),t&&Oe(t instanceof Error),Oe(typeof i=="function"),e.rmdir(r,n=>{n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")?kZ(r,e,i):n&&n.code==="ENOTDIR"?i(t):i(n)})}function kZ(r,e,t){Oe(r),Oe(e),Oe(typeof t=="function"),e.readdir(r,(i,n)=>{if(i)return t(i);let o=n.length,s;if(o===0)return e.rmdir(r,t);n.forEach(a=>{Eb(M1.join(r,a),e,l=>{if(!s){if(l)return t(s=l);--o==0&&e.rmdir(r,t)}})})})}function j1(r,e){let t;e=e||{},N1(e),Oe(r,"rimraf: missing path"),Oe.strictEqual(typeof r,"string","rimraf: path should be a string"),Oe(e,"rimraf: missing options"),Oe.strictEqual(typeof e,"object","rimraf: options should be object");try{t=e.lstatSync(r)}catch(i){if(i.code==="ENOENT")return;i.code==="EPERM"&&gc&&B1(r,e,i)}try{t&&t.isDirectory()?jd(r,e,null):e.unlinkSync(r)}catch(i){if(i.code==="ENOENT")return;if(i.code==="EPERM")return gc?B1(r,e,i):jd(r,e,i);if(i.code!=="EISDIR")throw i;jd(r,e,i)}}function jd(r,e,t){Oe(r),Oe(e),t&&Oe(t instanceof Error);try{e.rmdirSync(r)}catch(i){if(i.code==="ENOTDIR")throw t;if(i.code==="ENOTEMPTY"||i.code==="EEXIST"||i.code==="EPERM")IZ(r,e);else if(i.code!=="ENOENT")throw i}}function IZ(r,e){if(Oe(r),Oe(e),e.readdirSync(r).forEach(t=>j1(M1.join(r,t),e)),gc){let t=Date.now();do try{return e.rmdirSync(r,e)}catch(i){}while(Date.now()-t<500)}else return e.rmdirSync(r,e)}O1.exports=Eb;Eb.sync=j1});var vc=g((mEe,W1)=>{"use strict";var FZ=Er().fromCallback,H1=U1();W1.exports={remove:FZ(H1),removeSync:H1.sync}});var Z1=g((gEe,z1)=>{"use strict";var AZ=Er().fromCallback,G1=Ce(),V1=require("path"),K1=Br(),J1=vc(),Y1=AZ(function(e,t){t=t||function(){},G1.readdir(e,(i,n)=>{if(i)return K1.mkdirs(e,t);n=n.map(s=>V1.join(e,s)),o();function o(){let s=n.pop();if(!s)return t();J1.remove(s,a=>{if(a)return t(a);o()})}})});function X1(r){let e;try{e=G1.readdirSync(r)}catch(t){return K1.mkdirsSync(r)}e.forEach(t=>{t=V1.join(r,t),J1.removeSync(t)})}z1.exports={emptyDirSync:X1,emptydirSync:X1,emptyDir:Y1,emptydir:Y1}});var rk=g((vEe,Q1)=>{"use strict";var OZ=Er().fromCallback,ek=require("path"),yc=Ce(),tk=Br(),LZ=fn().pathExists;function MZ(r,e){function t(){yc.writeFile(r,"",i=>{if(i)return e(i);e()})}yc.stat(r,(i,n)=>{if(!i&&n.isFile())return e();let o=ek.dirname(r);LZ(o,(s,a)=>{if(s)return e(s);if(a)return t();tk.mkdirs(o,l=>{if(l)return e(l);t()})})})}function NZ(r){let e;try{e=yc.statSync(r)}catch(i){}if(e&&e.isFile())return;let t=ek.dirname(r);yc.existsSync(t)||tk.mkdirsSync(t),yc.writeFileSync(r,"")}Q1.exports={createFile:OZ(MZ),createFileSync:NZ}});var ak=g((yEe,ik)=>{"use strict";var qZ=Er().fromCallback,nk=require("path"),Cs=Ce(),ok=Br(),sk=fn().pathExists;function $Z(r,e,t){function i(n,o){Cs.link(n,o,s=>{if(s)return t(s);t(null)})}sk(e,(n,o)=>{if(n)return t(n);if(o)return t(null);Cs.lstat(r,s=>{if(s)return s.message=s.message.replace("lstat","ensureLink"),t(s);let a=nk.dirname(e);sk(a,(l,u)=>{if(l)return t(l);if(u)return i(r,e);ok.mkdirs(a,c=>{if(c)return t(c);i(r,e)})})})})}function BZ(r,e){if(Cs.existsSync(e))return;try{Cs.lstatSync(r)}catch(o){throw o.message=o.message.replace("lstat","ensureLink"),o}let i=nk.dirname(e);return Cs.existsSync(i)||ok.mkdirsSync(i),Cs.linkSync(r,e)}ik.exports={createLink:qZ($Z),createLinkSync:BZ}});var uk=g((bEe,lk)=>{"use strict";var vo=require("path"),bc=Ce(),jZ=fn().pathExists;function UZ(r,e,t){if(vo.isAbsolute(r))return bc.lstat(r,i=>i?(i.message=i.message.replace("lstat","ensureSymlink"),t(i)):t(null,{toCwd:r,toDst:r}));{let i=vo.dirname(e),n=vo.join(i,r);return jZ(n,(o,s)=>o?t(o):s?t(null,{toCwd:n,toDst:r}):bc.lstat(r,a=>a?(a.message=a.message.replace("lstat","ensureSymlink"),t(a)):t(null,{toCwd:r,toDst:vo.relative(i,r)})))}}function WZ(r,e){let t;if(vo.isAbsolute(r)){if(t=bc.existsSync(r),!t)throw new Error("absolute srcpath does not exist");return{toCwd:r,toDst:r}}else{let i=vo.dirname(e),n=vo.join(i,r);if(t=bc.existsSync(n),t)return{toCwd:n,toDst:r};if(t=bc.existsSync(r),!t)throw new Error("relative srcpath does not exist");return{toCwd:r,toDst:vo.relative(i,r)}}}lk.exports={symlinkPaths:UZ,symlinkPathsSync:WZ}});var pk=g((wEe,ck)=>{"use strict";var fk=Ce();function HZ(r,e,t){if(t=typeof e=="function"?e:t,e=typeof e=="function"?!1:e,e)return t(null,e);fk.lstat(r,(i,n)=>{if(i)return t(null,"file");e=n&&n.isDirectory()?"dir":"file",t(null,e)})}function zZ(r,e){let t;if(e)return e;try{t=fk.lstatSync(r)}catch(i){return"file"}return t&&t.isDirectory()?"dir":"file"}ck.exports={symlinkType:HZ,symlinkTypeSync:zZ}});var bk=g((xEe,dk)=>{"use strict";var GZ=Er().fromCallback,hk=require("path"),Ba=Ce(),mk=Br(),VZ=mk.mkdirs,KZ=mk.mkdirsSync,gk=uk(),JZ=gk.symlinkPaths,YZ=gk.symlinkPathsSync,vk=pk(),XZ=vk.symlinkType,ZZ=vk.symlinkTypeSync,yk=fn().pathExists;function QZ(r,e,t,i){i=typeof t=="function"?t:i,t=typeof t=="function"?!1:t,yk(e,(n,o)=>{if(n)return i(n);if(o)return i(null);JZ(r,e,(s,a)=>{if(s)return i(s);r=a.toDst,XZ(a.toCwd,t,(l,u)=>{if(l)return i(l);let c=hk.dirname(e);yk(c,(f,p)=>{if(f)return i(f);if(p)return Ba.symlink(r,e,u,i);VZ(c,d=>{if(d)return i(d);Ba.symlink(r,e,u,i)})})})})})}function eQ(r,e,t){if(Ba.existsSync(e))return;let n=YZ(r,e);r=n.toDst,t=ZZ(n.toCwd,t);let o=hk.dirname(e);return Ba.existsSync(o)||KZ(o),Ba.symlinkSync(r,e,t)}dk.exports={createSymlink:GZ(QZ),createSymlinkSync:eQ}});var xk=g((DEe,wk)=>{"use strict";var Ud=rk(),Wd=ak(),Hd=bk();wk.exports={createFile:Ud.createFile,createFileSync:Ud.createFileSync,ensureFile:Ud.createFile,ensureFileSync:Ud.createFileSync,createLink:Wd.createLink,createLinkSync:Wd.createLinkSync,ensureLink:Wd.createLink,ensureLinkSync:Wd.createLinkSync,createSymlink:Hd.createSymlink,createSymlinkSync:Hd.createSymlinkSync,ensureSymlink:Hd.createSymlink,ensureSymlinkSync:Hd.createSymlinkSync}});var Ck=g((SEe,Dk)=>{var ja;try{ja=Ce()}catch(r){ja=require("fs")}function tQ(r,e,t){t==null&&(t=e,e={}),typeof e=="string"&&(e={encoding:e}),e=e||{};var i=e.fs||ja,n=!0;"throws"in e&&(n=e.throws),i.readFile(r,e,function(o,s){if(o)return t(o);s=Sk(s);var a;try{a=JSON.parse(s,e?e.reviver:null)}catch(l){return n?(l.message=r+": "+l.message,t(l)):t(null,null)}t(null,a)})}function rQ(r,e){e=e||{},typeof e=="string"&&(e={encoding:e});var t=e.fs||ja,i=!0;"throws"in e&&(i=e.throws);try{var n=t.readFileSync(r,e);return n=Sk(n),JSON.parse(n,e.reviver)}catch(o){if(i)throw o.message=r+": "+o.message,o;return null}}function Ek(r,e){var t,i=` +`;typeof e=="object"&&e!==null&&(e.spaces&&(t=e.spaces),e.EOL&&(i=e.EOL));var n=JSON.stringify(r,e?e.replacer:null,t);return n.replace(/\n/g,i)+i}function iQ(r,e,t,i){i==null&&(i=t,t={}),t=t||{};var n=t.fs||ja,o="";try{o=Ek(e,t)}catch(s){i&&i(s,null);return}n.writeFile(r,o,t,i)}function nQ(r,e,t){t=t||{};var i=t.fs||ja,n=Ek(e,t);return i.writeFileSync(r,n,t)}function Sk(r){return Buffer.isBuffer(r)&&(r=r.toString("utf8")),r=r.replace(/^\uFEFF/,""),r}var oQ={readFile:tQ,readFileSync:rQ,writeFile:iQ,writeFileSync:nQ};Dk.exports=oQ});var Gd=g((EEe,_k)=>{"use strict";var Pk=Er().fromCallback,zd=Ck();_k.exports={readJson:Pk(zd.readFile),readJsonSync:zd.readFileSync,writeJson:Pk(zd.writeFile),writeJsonSync:zd.writeFileSync}});var kk=g((CEe,Tk)=>{"use strict";var sQ=require("path"),aQ=Br(),lQ=fn().pathExists,Rk=Gd();function uQ(r,e,t,i){typeof t=="function"&&(i=t,t={});let n=sQ.dirname(r);lQ(n,(o,s)=>{if(o)return i(o);if(s)return Rk.writeJson(r,e,t,i);aQ.mkdirs(n,a=>{if(a)return i(a);Rk.writeJson(r,e,t,i)})})}Tk.exports=uQ});var Fk=g((_Ee,Ik)=>{"use strict";var cQ=Ce(),fQ=require("path"),pQ=Br(),dQ=Gd();function hQ(r,e,t){let i=fQ.dirname(r);cQ.existsSync(i)||pQ.mkdirsSync(i),dQ.writeJsonSync(r,e,t)}Ik.exports=hQ});var Ok=g((PEe,Ak)=>{"use strict";var mQ=Er().fromCallback,mr=Gd();mr.outputJson=mQ(kk());mr.outputJsonSync=Fk();mr.outputJSON=mr.outputJson;mr.outputJSONSync=mr.outputJsonSync;mr.writeJSON=mr.writeJson;mr.writeJSONSync=mr.writeJsonSync;mr.readJSON=mr.readJson;mr.readJSONSync=mr.readJsonSync;Ak.exports=mr});var Bk=g((TEe,Lk)=>{"use strict";var Mk=Ce(),gQ=require("path"),vQ=xb().copySync,Nk=vc().removeSync,yQ=Br().mkdirpSync,qk=fc();function wQ(r,e,t){t=t||{};let i=t.overwrite||t.clobber||!1,{srcStat:n}=qk.checkPathsSync(r,e,"move");return qk.checkParentPathsSync(r,n,e,"move"),yQ(gQ.dirname(e)),bQ(r,e,i)}function bQ(r,e,t){if(t)return Nk(e),$k(r,e,t);if(Mk.existsSync(e))throw new Error("dest already exists.");return $k(r,e,t)}function $k(r,e,t){try{Mk.renameSync(r,e)}catch(i){if(i.code!=="EXDEV")throw i;return xQ(r,e,t)}}function xQ(r,e,t){return vQ(r,e,{overwrite:t,errorOnExist:!0}),Nk(r)}Lk.exports=wQ});var Uk=g((REe,jk)=>{"use strict";jk.exports={moveSync:Bk()}});var Vk=g((kEe,Wk)=>{"use strict";var DQ=Ce(),SQ=require("path"),EQ=Sb().copy,Hk=vc().remove,CQ=Br().mkdirp,_Q=fn().pathExists,zk=fc();function TQ(r,e,t,i){typeof t=="function"&&(i=t,t={});let n=t.overwrite||t.clobber||!1;zk.checkPaths(r,e,"move",(o,s)=>{if(o)return i(o);let{srcStat:a}=s;zk.checkParentPaths(r,a,e,"move",l=>{if(l)return i(l);CQ(SQ.dirname(e),u=>u?i(u):PQ(r,e,n,i))})})}function PQ(r,e,t,i){if(t)return Hk(e,n=>n?i(n):Gk(r,e,t,i));_Q(e,(n,o)=>n?i(n):o?i(new Error("dest already exists.")):Gk(r,e,t,i))}function Gk(r,e,t,i){DQ.rename(r,e,n=>n?n.code!=="EXDEV"?i(n):RQ(r,e,t,i):i())}function RQ(r,e,t,i){EQ(r,e,{overwrite:t,errorOnExist:!0},o=>o?i(o):Hk(r,i))}Wk.exports=TQ});var Jk=g((IEe,Kk)=>{"use strict";var kQ=Er().fromCallback;Kk.exports={move:kQ(Vk())}});var Qk=g((FEe,Yk)=>{"use strict";var IQ=Er().fromCallback,wc=Ce(),Xk=require("path"),Zk=Br(),FQ=fn().pathExists;function AQ(r,e,t,i){typeof t=="function"&&(i=t,t="utf8");let n=Xk.dirname(r);FQ(n,(o,s)=>{if(o)return i(o);if(s)return wc.writeFile(r,e,t,i);Zk.mkdirs(n,a=>{if(a)return i(a);wc.writeFile(r,e,t,i)})})}function OQ(r,...e){let t=Xk.dirname(r);if(wc.existsSync(t))return wc.writeFileSync(r,...e);Zk.mkdirsSync(t),wc.writeFileSync(r,...e)}Yk.exports={outputFile:IQ(AQ),outputFileSync:OQ}});var _b=g((AEe,Cb)=>{"use strict";Cb.exports=Object.assign({},lb(),xb(),Sb(),Z1(),xk(),Ok(),Br(),Uk(),Jk(),Qk(),fn(),vc());var eI=require("fs");Object.getOwnPropertyDescriptor(eI,"promises")&&Object.defineProperty(Cb.exports,"promises",{get(){return eI.promises}})});var rI=g((OEe,tI)=>{tI.exports=()=>new Date});var Pb=g((LEe,di)=>{"use strict";function iI(r,e){for(var t=r.toString();t.length-1,i=_s(Ps(e,t,"Date")),n=_s(Ps(e,t,"Month")+1),o=_s(Ps(e,t,"FullYear")),s=_s(o.substring(2,4)),a=r.indexOf("yyyy")>-1?o:s,l=_s(Ps(e,t,"Hours")),u=_s(Ps(e,t,"Minutes")),c=_s(Ps(e,t,"Seconds")),f=iI(Ps(e,t,"Milliseconds"),3),p=LQ(e.getTimezoneOffset()),d=r.replace(/dd/g,i).replace(/MM/g,n).replace(/y{1,4}/g,a).replace(/hh/g,l).replace(/mm/g,u).replace(/ss/g,c).replace(/SSS/g,f).replace(/O/g,p);return d}function MQ(r,e,t){var i=[{pattern:/y{1,4}/,regexp:"\\d{1,4}",fn:function(u,c){u.setFullYear(c)}},{pattern:/MM/,regexp:"\\d{1,2}",fn:function(u,c){u.setMonth(c-1)}},{pattern:/dd/,regexp:"\\d{1,2}",fn:function(u,c){u.setDate(c)}},{pattern:/hh/,regexp:"\\d{1,2}",fn:function(u,c){u.setHours(c)}},{pattern:/mm/,regexp:"\\d\\d",fn:function(u,c){u.setMinutes(c)}},{pattern:/ss/,regexp:"\\d\\d",fn:function(u,c){u.setSeconds(c)}},{pattern:/SSS/,regexp:"\\d\\d\\d",fn:function(u,c){u.setMilliseconds(c)}},{pattern:/O/,regexp:"[+-]\\d{3,4}|Z",fn:function(u,c){c==="Z"&&(c=0);var f=Math.abs(c),p=f%100+Math.floor(f/100)*60;u.setMinutes(u.getMinutes()+(c>0?p:-p))}}],n=i.reduce(function(u,c){return c.pattern.test(u.regexp)?(c.index=u.regexp.match(c.pattern).index,u.regexp=u.regexp.replace(c.pattern,"("+c.regexp+")")):c.index=-1,u},{regexp:r,index:[]}),o=i.filter(function(u){return u.index>-1});o.sort(function(u,c){return u.index-c.index});var s=new RegExp(n.regexp),a=s.exec(e);if(a){var l=t||di.exports.now();return o.forEach(function(u,c){u.fn(l,a[c+1])}),l}throw new Error("String '"+e+"' could not be parsed as '"+r+"'")}function NQ(r,e,t){if(!r)throw new Error("pattern must be supplied");return MQ(r,e,t)}function qQ(){return new Date}di.exports=nI;di.exports.asString=nI;di.exports.parse=NQ;di.exports.now=qQ;di.exports.ISO8601_FORMAT="yyyy-MM-ddThh:mm:ss.SSS";di.exports.ISO8601_WITH_TZ_OFFSET_FORMAT="yyyy-MM-ddThh:mm:ss.SSSO";di.exports.DATETIME_FORMAT="dd MM yyyy hh:mm:ss.SSS";di.exports.ABSOLUTETIME_FORMAT="hh:mm:ss.SSS"});var aI=g((MEe,oI)=>{var $Q=gt()("streamroller:fileNameFormatter"),BQ=require("path"),sI=".",jQ=".gz";oI.exports=({file:r,keepFileExt:e,needsIndex:t,alwaysIncludeDate:i,compress:n})=>{let o=BQ.join(r.dir,r.name),s=f=>f+r.ext,a=(f,p,d)=>(t||!d)&&p?f+sI+p:f,l=(f,p,d)=>(p>0||i)&&d?f+sI+d:f,u=(f,p)=>p&&n?f+jQ:f,c=e?[l,a,s,u]:[s,l,a,u];return({date:f,index:p})=>($Q(`_formatFileName: date=${f}, index=${p}`),c.reduce((d,h)=>h(d,p,f),o))}});var fI=g((NEe,lI)=>{var Ts=gt()("streamroller:fileNameParser"),UQ=".",uI=".gz",cI=Pb();lI.exports=({file:r,keepFileExt:e,pattern:t})=>{let i=(c,f)=>c.endsWith(uI)?(Ts("it is gzipped"),f.isCompressed=!0,c.slice(0,-1*uI.length)):c,n="__NOT_MATCHING__",u=[i,e?c=>c.startsWith(r.name)&&c.endsWith(r.ext)?(Ts("it starts and ends with the right things"),c.slice(r.name.length+1,-1*r.ext.length)):n:c=>c.startsWith(r.base)?(Ts("it starts with the right things"),c.slice(r.base.length+1)):n,t?(c,f)=>{let p=c.split(UQ),d=p[p.length-1];Ts("items: ",p,", indexStr: ",d);let h=c;d!==void 0&&d.match(/^\d+$/)?(h=c.slice(0,-1*(d.length+1)),Ts(`dateStr is ${h}`),t&&!h&&(h=d,d="0")):d="0";try{let m=cI.parse(t,h,new Date(0,0));return cI.asString(t,m)!==h?c:(f.index=parseInt(d,10),f.date=h,f.timestamp=m.getTime(),"")}catch(m){return Ts(`Problem parsing ${h} as ${t}, error was: `,m),c}}:(c,f)=>c.match(/^\d+$/)?(Ts("it has an index"),f.index=parseInt(c,10),""):c];return c=>{let f={filename:c,index:0,isCompressed:!1};return u.reduce((d,h)=>h(d,f),c)?null:f}}});var dI=g((qEe,pI)=>{var Rs=gt()("streamroller:moveAndMaybeCompressFile"),yo=_b(),WQ=require("zlib"),HQ=async(r,e,t)=>{if(r===e){Rs("moveAndMaybeCompressFile: source and target are the same, not doing anything");return}if(await yo.pathExists(r))if(Rs(`moveAndMaybeCompressFile: moving file from ${r} to ${e} ${t?"with":"without"} compress`),t)await new Promise((i,n)=>{yo.createReadStream(r).pipe(WQ.createGzip()).pipe(yo.createWriteStream(e)).on("finish",()=>{Rs(`moveAndMaybeCompressFile: finished compressing ${e}, deleting ${r}`),yo.unlink(r).then(i).catch(()=>{Rs(`Deleting ${r} failed, truncating instead`),yo.truncate(r).then(i).catch(n)})})});else{Rs(`moveAndMaybeCompressFile: deleting file=${e}, renaming ${r} to ${e}`);try{await yo.move(r,e,{overwrite:!0})}catch(i){Rs(`moveAndMaybeCompressFile: error moving ${r} to ${e}`,i),Rs("Trying copy+truncate instead"),await yo.copy(r,e,{overwrite:!0}),await yo.truncate(r)}}};pI.exports=HQ});var Yd=g(($Ee,hI)=>{var jr=gt()("streamroller:RollingFileWriteStream"),xc=_b(),Vd=require("path"),Kd=rI(),Jd=Pb(),{Writable:zQ}=require("stream"),GQ=aI(),VQ=fI(),KQ=dI(),mI=class extends zQ{constructor(e,t){jr(`constructor: creating RollingFileWriteStream. path=${e}`),super(t),this.options=this._parseOption(t),this.fileObject=Vd.parse(e),this.fileObject.dir===""&&(this.fileObject=Vd.parse(Vd.join(process.cwd(),e))),this.fileFormatter=GQ({file:this.fileObject,alwaysIncludeDate:this.options.alwaysIncludePattern,needsIndex:this.options.maxSize 0`);if(i.numToKeep<=0)throw new Error(`options.numToKeep (${i.numToKeep}) should be > 0`);return jr(`_parseOption: creating stream with option=${JSON.stringify(i)}`),i}_final(e){this.currentFileStream.end("",this.options.encoding,e)}_write(e,t,i){this._shouldRoll().then(()=>{jr(`_write: writing chunk. file=${this.currentFileStream.path} state=${JSON.stringify(this.state)} chunk=${e}`),this.currentFileStream.write(e,t,n=>{this.state.currentSize+=e.length,i(n)})})}async _shouldRoll(){(this._dateChanged()||this._tooBig())&&(jr(`_shouldRoll: rolling because dateChanged? ${this._dateChanged()} or tooBig? ${this._tooBig()}`),await this._roll())}_dateChanged(){return this.state.currentDate&&this.state.currentDate!==Jd(this.options.pattern,Kd())}_tooBig(){return this.state.currentSize>=this.options.maxSize}_roll(){return jr("_roll: closing the current stream"),new Promise((e,t)=>{this.currentFileStream.end("",this.options.encoding,()=>{this._moveOldFiles().then(e).catch(t)})})}async _moveOldFiles(){let e=await this._getExistingFiles(),t=this.state.currentDate?e.filter(i=>i.date===this.state.currentDate):e;for(let i=t.length;i>=0;i--){jr(`_moveOldFiles: i = ${i}`);let n=this.fileFormatter({date:this.state.currentDate,index:i}),o=this.fileFormatter({date:this.state.currentDate,index:i+1});await KQ(n,o,this.options.compress&&i===0)}this.state.currentSize=0,this.state.currentDate=this.state.currentDate?Jd(this.options.pattern,Kd()):null,jr(`_moveOldFiles: finished rolling files. state=${JSON.stringify(this.state)}`),this._renewWriteStream(),await new Promise((i,n)=>{this.currentFileStream.write("","utf8",()=>{this._clean().then(i).catch(n)})})}async _getExistingFiles(){let e=await xc.readdir(this.fileObject.dir).catch(()=>[]);jr(`_getExistingFiles: files=${e}`);let t=e.map(n=>this.fileNameParser(n)).filter(n=>n),i=n=>(n.timestamp?n.timestamp:Kd().getTime())-n.index;return t.sort((n,o)=>i(n)-i(o)),t}_renewWriteStream(){xc.ensureDirSync(this.fileObject.dir);let e=this.fileFormatter({date:this.state.currentDate,index:0}),t={flags:this.options.flags,encoding:this.options.encoding,mode:this.options.mode};this.currentFileStream=xc.createWriteStream(e,t),this.currentFileStream.on("error",i=>{this.emit("error",i)})}async _clean(){let e=await this._getExistingFiles();if(jr(`_clean: numToKeep = ${this.options.numToKeep}, existingFiles = ${e.length}`),jr("_clean: existing files are: ",e),this._tooManyFiles(e.length)){let t=e.slice(0,e.length-this.options.numToKeep-1).map(i=>Vd.format({dir:this.fileObject.dir,base:i.filename}));await JQ(t)}}_tooManyFiles(e){return this.options.numToKeep>0&&e>this.options.numToKeep}},JQ=r=>(jr(`deleteFiles: files to delete: ${r}`),Promise.all(r.map(e=>xc.unlink(e).catch(t=>{jr(`deleteFiles: error when unlinking ${e}, ignoring. Error was ${t}`)}))));hI.exports=mI});var yI=g((BEe,gI)=>{var YQ=Yd(),vI=class extends YQ{constructor(e,t,i,n){n||(n={}),t&&(n.maxSize=t),i||(i=1),n.numToKeep=i,super(e,n),this.backups=this.options.numToKeep,this.size=this.options.maxSize}get theStream(){return this.currentFileStream}};gI.exports=vI});var xI=g((jEe,bI)=>{var XQ=Yd(),wI=class extends XQ{constructor(e,t,i){t&&typeof t=="object"&&(i=t,t=null),i||(i={}),t||(t="yyyy-MM-dd"),i.daysToKeep&&(i.numToKeep=i.daysToKeep),t.startsWith(".")&&(t=t.substring(1)),i.pattern=t,super(e,i),this.mode=this.options.mode}get theStream(){return this.currentFileStream}};bI.exports=wI});var Tb=g((UEe,DI)=>{DI.exports={RollingFileWriteStream:Yd(),RollingFileStream:yI(),DateRollingFileStream:xI()}});var _I=g((WEe,SI)=>{var EI=gt()("log4js:file"),ZQ=require("path"),QQ=Tb(),eee=require("os"),tee=eee.EOL;function CI(r,e,t,i){let n=new QQ.RollingFileStream(r,e,t,i);return n.on("error",o=>{console.error("log4js.fileAppender - Writing to file %s, error happened ",r,o)}),n.on("drain",()=>{process.emit("log4js:pause",!1)}),n}function ree(r,e,t,i,n,o){r=ZQ.normalize(r),i=i===void 0?5:i,i=i===0?1:i,EI("Creating file appender (",r,", ",t,", ",i,", ",n,", ",o,")");let s=CI(r,t,i,n),a=function(l){if(n.removeColor===!0){let u=/\x1b[[0-9;]*m/g;l.data=l.data.map(c=>typeof c=="string"?c.replace(u,""):c)}s.write(e(l,o)+tee,"utf8")||process.emit("log4js:pause",!0)};return a.reopen=function(){s.end(()=>{s=CI(r,t,i,n)})},a.sighupHandler=function(){EI("SIGHUP handler called."),a.reopen()},a.shutdown=function(l){process.removeListener("SIGHUP",a.sighupHandler),s.end("","utf-8",l)},process.on("SIGHUP",a.sighupHandler),a}function iee(r,e){let t=e.basicLayout;return r.layout&&(t=e.layout(r.layout.type,r.layout)),ree(r.filename,t,r.maxLogSize,r.backups,r,r.timezoneOffset)}SI.exports.configure=iee});var TI=g((HEe,PI)=>{var nee=Tb(),oee=require("os"),see=oee.EOL;function aee(r,e,t,i,n){i.maxSize=i.maxLogSize;let o=new nee.DateRollingFileStream(r,e,i);o.on("drain",()=>{process.emit("log4js:pause",!1)});let s=function(a){o.write(t(a,n)+see,"utf8")||process.emit("log4js:pause",!0)};return s.shutdown=function(a){o.write("","utf-8",()=>{o.end(a)})},s}function lee(r,e){let t=e.basicLayout;return r.layout&&(t=e.layout(r.layout.type,r.layout)),r.alwaysIncludePattern||(r.alwaysIncludePattern=!1),aee(r.filename,r.pattern,t,r,r.timezoneOffset)}PI.exports.configure=lee});var FI=g((zEe,RI)=>{var An=gt()("log4js:fileSync"),Ua=require("path"),On=require("fs"),uee=require("os"),cee=uee.EOL||` +`;function kI(r,e){if(On.existsSync(r))return;let t=On.openSync(r,e.flags,e.mode);On.closeSync(t)}var II=class{constructor(e,t,i,n){An("In RollingFileStream");function o(){if(!e||!t||t<=0)throw new Error("You must specify a filename and file size")}o(),this.filename=e,this.size=t,this.backups=i||1,this.options=n,this.currentSize=0;function s(a){let l=0;try{l=On.statSync(a).size}catch(u){kI(a,n)}return l}this.currentSize=s(this.filename)}shouldRoll(){return An("should roll with current size %d, and max size %d",this.currentSize,this.size),this.currentSize>=this.size}roll(e){let t=this,i=new RegExp(`^${Ua.basename(e)}`);function n(u){return i.test(u)}function o(u){return parseInt(u.substring(`${Ua.basename(e)}.`.length),10)||0}function s(u,c){return o(u)>o(c)?1:o(u) ${e}.${c+1}`),On.renameSync(Ua.join(Ua.dirname(e),u),`${e}.${c+1}`)}}function l(){An("Renaming the old files"),On.readdirSync(Ua.dirname(e)).filter(n).sort(s).reverse().forEach(a)}An("Rolling, rolling, rolling"),l()}write(e,t){let i=this;function n(){An("writing the chunk to the file"),i.currentSize+=e.length,On.appendFileSync(i.filename,e)}An("in write"),this.shouldRoll()&&(this.currentSize=0,this.roll(this.filename)),n()}};function fee(r,e,t,i,n,o){An("fileSync appender created"),r=Ua.normalize(r),i=i===void 0?5:i,i=i===0?1:i;function s(l,u,c){let f;return u?f=new II(l,u,c,o):f=(p=>(kI(p,o),{write(d){On.appendFileSync(p,d)}}))(l),f}let a=s(r,t,i);return l=>{a.write(e(l,n)+cee)}}function pee(r,e){let t=e.basicLayout;r.layout&&(t=e.layout(r.layout.type,r.layout));let i={flags:r.flags||"a",encoding:r.encoding||"utf8",mode:r.mode||420};return fee(r.filename,t,r.maxLogSize,r.backups,r.timezoneOffset,i)}RI.exports.configure=pee});var kb=g((GEe,AI)=>{var dee=require("path"),ks=gt()("log4js:appenders"),hi=bs(),OI=Ld(),hee=Ds(),mee=eb(),gee=TR(),pn=new Map;pn.set("console",kR());pn.set("stdout",FR());pn.set("stderr",OR());pn.set("logLevelFilter",MR());pn.set("categoryFilter",$R());pn.set("noLogFilter",UR());pn.set("file",_I());pn.set("dateFile",TI());pn.set("fileSync",FI());var Dc=new Map,Rb=(r,e)=>{ks("Loading module from ",r);try{return require(r)}catch(t){hi.throwExceptionIf(e,t.code!=="MODULE_NOT_FOUND",`appender "${r}" could not be loaded (error was: ${t})`);return}},vee=(r,e)=>pn.get(r)||Rb(`./${r}`,e)||Rb(r,e)||""||Rb(dee.join(process.cwd(),r),e),Xd=new Set,LI=(r,e)=>{if(Dc.has(r))return Dc.get(r);if(!e.appenders[r])return!1;if(Xd.has(r))throw new Error(`Dependency loop detected for appender ${r}.`);Xd.add(r),ks(`Creating appender ${r}`);let t=yee(r,e);return Xd.delete(r),Dc.set(r,t),t},yee=(r,e)=>{let t=e.appenders[r],i=t.type.configure?t.type:vee(t.type,e);return hi.throwExceptionIf(e,hi.not(i),`appender "${r}" is not valid (type "${t.type}" could not be found)`),i.appender&&ks(`DEPRECATION: Appender ${t.type} exports an appender function.`),i.shutdown&&ks(`DEPRECATION: Appender ${t.type} exports a shutdown function.`),ks(`${r}: clustering.isMaster ? ${OI.isMaster()}`),ks(`${r}: appenderModule is ${require("util").inspect(i)}`),OI.onlyOnMaster(()=>(ks(`calling appenderModule.configure for ${r} / ${t.type}`),i.configure(gee.modifyConfig(t),mee,n=>LI(n,e),hee)),()=>{})},MI=r=>{Dc.clear(),Xd.clear();let e=[];Object.values(r.categories).forEach(t=>{e.push(...t.appenders)}),Object.keys(r.appenders).forEach(t=>{(e.includes(t)||r.appenders[t].type==="tcp-server")&&LI(t,r)})};MI({appenders:{out:{type:"stdout"}},categories:{default:{appenders:["out"],level:"trace"}}});hi.addListener(r=>{hi.throwExceptionIf(r,hi.not(hi.anObject(r.appenders)),'must have a property "appenders" of type object.');let e=Object.keys(r.appenders);hi.throwExceptionIf(r,hi.not(e.length),"must define at least one appender."),e.forEach(t=>{hi.throwExceptionIf(r,hi.not(r.appenders[t].type),`appender "${t}" is not valid (must be an object with property "type")`)})});hi.addListener(MI);AI.exports=Dc});var Fb=g((VEe,NI)=>{var Is=gt()("log4js:categories"),at=bs(),Ib=Ds(),qI=kb(),Wa=new Map;function $I(r,e,t){if(e.inherit===!1)return;let i=t.lastIndexOf(".");if(i<0)return;let n=t.substring(0,i),o=r.categories[n];o||(o={inherit:!0,appenders:[]}),$I(r,o,n),!r.categories[n]&&o.appenders&&o.appenders.length&&o.level&&(r.categories[n]=o),e.appenders=e.appenders||[],e.level=e.level||o.level,o.appenders.forEach(s=>{e.appenders.includes(s)||e.appenders.push(s)}),e.parent=o}function bee(r){if(!r.categories)return;Object.keys(r.categories).forEach(t=>{let i=r.categories[t];$I(r,i,t)})}at.addPreProcessingListener(r=>bee(r));at.addListener(r=>{at.throwExceptionIf(r,at.not(at.anObject(r.categories)),'must have a property "categories" of type object.');let e=Object.keys(r.categories);at.throwExceptionIf(r,at.not(e.length),"must define at least one category."),e.forEach(t=>{let i=r.categories[t];at.throwExceptionIf(r,[at.not(i.appenders),at.not(i.level)],`category "${t}" is not valid (must be an object with properties "appenders" and "level")`),at.throwExceptionIf(r,at.not(Array.isArray(i.appenders)),`category "${t}" is not valid (appenders must be an array of appender names)`),at.throwExceptionIf(r,at.not(i.appenders.length),`category "${t}" is not valid (appenders must contain at least one appender name)`),Object.prototype.hasOwnProperty.call(i,"enableCallStack")&&at.throwExceptionIf(r,typeof i.enableCallStack!="boolean",`category "${t}" is not valid (enableCallStack must be boolean type)`),i.appenders.forEach(n=>{at.throwExceptionIf(r,at.not(qI.get(n)),`category "${t}" is not valid (appender "${n}" is not defined)`)}),at.throwExceptionIf(r,at.not(Ib.getLevel(i.level)),`category "${t}" is not valid (level "${i.level}" not recognised; valid levels are ${Ib.levels.join(", ")})`)}),at.throwExceptionIf(r,at.not(r.categories.default),'must define a "default" category.')});var BI=r=>{Wa.clear(),Object.keys(r.categories).forEach(t=>{let i=r.categories[t],n=[];i.appenders.forEach(o=>{n.push(qI.get(o)),Is(`Creating category ${t}`),Wa.set(t,{appenders:n,level:Ib.getLevel(i.level),enableCallStack:i.enableCallStack||!1})})})};BI({categories:{default:{appenders:["out"],level:"OFF"}}});at.addListener(BI);var Fs=r=>(Is(`configForCategory: searching for config for ${r}`),Wa.has(r)?(Is(`configForCategory: ${r} exists in config, returning it`),Wa.get(r)):r.indexOf(".")>0?(Is(`configForCategory: ${r} has hierarchy, searching for parents`),Fs(r.substring(0,r.lastIndexOf(".")))):(Is("configForCategory: returning config for default category"),Fs("default"))),wee=r=>Fs(r).appenders,xee=r=>Fs(r).level,Dee=(r,e)=>{let t=Wa.get(r);if(Is(`setLevelForCategory: found ${t} for ${r}`),!t){let i=Fs(r);Is(`setLevelForCategory: no config found for category, found ${i} for parents of ${r}`),t={appenders:i.appenders}}t.level=e,Wa.set(r,t)},See=r=>Fs(r).enableCallStack===!0,Eee=(r,e)=>{Fs(r).enableCallStack=e};NI.exports={appendersForCategory:wee,getLevelForCategory:xee,setLevelForCategory:Dee,getEnableCallStackForCategory:See,setEnableCallStackForCategory:Eee}});var HI=g((KEe,jI)=>{var UI=gt()("log4js:logger"),Cee=rb(),bo=Ds(),_ee=Ld(),Zd=Fb(),Pee=bs(),Tee=/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/;function Ree(r,e=4){let t=r.stack.split(` +`).slice(e),i=Tee.exec(t[0]);return i&&i.length===6?{functionName:i[1],fileName:i[2],lineNumber:parseInt(i[3],10),columnNumber:parseInt(i[4],10),callStack:t.join(` +`)}:null}var Qd=class{constructor(e){if(!e)throw new Error("No category provided.");this.category=e,this.context={},this.parseCallStack=Ree,UI(`Logger created (${this.category}, ${this.level})`)}get level(){return bo.getLevel(Zd.getLevelForCategory(this.category),bo.TRACE)}set level(e){Zd.setLevelForCategory(this.category,bo.getLevel(e,this.level))}get useCallStack(){return Zd.getEnableCallStackForCategory(this.category)}set useCallStack(e){Zd.setEnableCallStackForCategory(this.category,e===!0)}log(e,...t){let i=bo.getLevel(e,bo.INFO);this.isLevelEnabled(i)&&this._log(i,t)}isLevelEnabled(e){return this.level.isLessThanOrEqualTo(e)}_log(e,t){UI(`sending log data (${e}) to appenders`);let i=new Cee(this.category,e,t,this.context,this.useCallStack&&this.parseCallStack(new Error));_ee.send(i)}addContext(e,t){this.context[e]=t}removeContext(e){delete this.context[e]}clearContext(){this.context={}}setParseCallStackFunction(e){this.parseCallStack=e}};function WI(r){let e=bo.getLevel(r),i=e.toString().toLowerCase().replace(/_([a-z])/g,o=>o[1].toUpperCase()),n=i[0].toUpperCase()+i.slice(1);Qd.prototype[`is${n}Enabled`]=function(){return this.isLevelEnabled(e)},Qd.prototype[i]=function(...o){this.log(e,...o)}}bo.levels.forEach(WI);Pee.addListener(()=>{bo.levels.forEach(WI)});jI.exports=Qd});var VI=g((JEe,zI)=>{var Ha=Ds(),kee=':remote-addr - - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"';function Iee(r){return r.originalUrl||r.url}function Fee(r,e,t){let i=o=>{let s=o.concat();for(let a=0;ai.source?i.source:i);e=new RegExp(t.join("|"))}return e}function Oee(r,e,t){let i=e;if(t){let n=t.find(o=>{let s=!1;return o.from&&o.to?s=r>=o.from&&r<=o.to:s=o.codes.indexOf(r)!==-1,s});n&&(i=Ha.getLevel(n.level,i))}return i}zI.exports=function(e,t){typeof t=="string"||typeof t=="function"?t={format:t}:t=t||{};let i=e,n=Ha.getLevel(t.level,Ha.INFO),o=t.format||kee,s=Aee(t.nolog);return(a,l,u)=>{if(a._logging||s&&s.test(a.originalUrl))return u();if(i.isLevelEnabled(n)||t.level==="auto"){let c=new Date,{writeHead:f}=l;a._logging=!0,l.writeHead=(p,d)=>{l.writeHead=f,l.writeHead(p,d),l.__statusCode=p,l.__headers=d||{}},l.on("finish",()=>{l.responseTime=new Date-c,l.statusCode&&t.level==="auto"&&(n=Ha.INFO,l.statusCode>=300&&(n=Ha.WARN),l.statusCode>=400&&(n=Ha.ERROR)),n=Oee(l.statusCode,n,t.statusRules);let p=Fee(a,l,t.tokens||[]);if(t.context&&i.addContext("res",l),typeof o=="function"){let d=o(a,l,h=>GI(h,p));d&&i.log(n,d)}else i.log(n,GI(o,p));t.context&&i.removeContext("res")})}return u()}}});var Ab=g((YEe,KI)=>{var wo=gt()("log4js:main"),Lee=require("fs"),Mee=XT()({proto:!0}),Nee=bs(),qee=eb(),$ee=Ds(),Bee=kb(),jee=Fb(),Uee=HI(),Wee=Ld(),Hee=VI(),eh=!1;function zee(r){if(!eh)return;wo("Received log event ",r),jee.appendersForCategory(r.categoryName).forEach(t=>{t(r)})}function Gee(r){wo(`Loading configuration from ${r}`);try{return JSON.parse(Lee.readFileSync(r,"utf8"))}catch(e){throw new Error(`Problem reading config from file "${r}". Error was ${e.message}`,e)}}function YI(r){let e=r;return typeof e=="string"&&(e=Gee(r)),wo(`Configuration is ${e}`),Nee.configure(Mee(e)),Wee.onMessage(zee),eh=!0,JI}function Vee(r){wo("Shutdown called. Disabling all log writing."),eh=!1;let e=Array.from(Bee.values()),t=e.reduceRight((s,a)=>a.shutdown?s+1:s,0),i=0,n;wo(`Found ${t} appenders with shutdown functions.`);function o(s){n=n||s,i+=1,wo(`Appender shutdowns complete: ${i} / ${t}`),i>=t&&(wo("All shutdown functions completed."),r&&r(n))}return t===0?(wo("No appenders with shutdown functions found."),r!==void 0&&r()):(e.filter(s=>s.shutdown).forEach(s=>s.shutdown(o)),null)}function Kee(r){return eh||YI(process.env.LOG4JS_CONFIG||{appenders:{out:{type:"stdout"}},categories:{default:{appenders:["out"],level:"OFF"}}}),new Uee(r||"default")}var JI={getLogger:Kee,configure:YI,shutdown:Vee,connectLogger:Hee,levels:$ee,addLayout:qee.addLayout};KI.exports=JI});var Ur=g(Ob=>{"use strict";Ob.fromCallback=function(r){return Object.defineProperty(function(...e){if(typeof e[e.length-1]=="function")r.apply(this,e);else return new Promise((t,i)=>{r.apply(this,e.concat([(n,o)=>n?i(n):t(o)]))})},"name",{value:r.name})};Ob.fromPromise=function(r){return Object.defineProperty(function(...e){let t=e[e.length-1];if(typeof t!="function")return r.apply(this,e);r.apply(this,e.slice(0,-1)).then(i=>t(null,i),t)},"name",{value:r.name})}});var Sc=g(xo=>{"use strict";var XI=Ur().fromCallback,gr=Ce(),Jee=["access","appendFile","chmod","chown","close","copyFile","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","lchmod","lchown","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rmdir","stat","symlink","truncate","unlink","utimes","writeFile"].filter(r=>typeof gr[r]=="function");Object.keys(gr).forEach(r=>{r!=="promises"&&(xo[r]=gr[r])});Jee.forEach(r=>{xo[r]=XI(gr[r])});xo.exists=function(r,e){return typeof e=="function"?gr.exists(r,e):new Promise(t=>gr.exists(r,t))};xo.read=function(r,e,t,i,n,o){return typeof o=="function"?gr.read(r,e,t,i,n,o):new Promise((s,a)=>{gr.read(r,e,t,i,n,(l,u,c)=>{if(l)return a(l);s({bytesRead:u,buffer:c})})})};xo.write=function(r,e,...t){return typeof t[t.length-1]=="function"?gr.write(r,e,...t):new Promise((i,n)=>{gr.write(r,e,...t,(o,s,a)=>{if(o)return n(o);i({bytesWritten:s,buffer:a})})})};typeof gr.writev=="function"&&(xo.writev=function(r,e,...t){return typeof t[t.length-1]=="function"?gr.writev(r,e,...t):new Promise((i,n)=>{gr.writev(r,e,...t,(o,s,a)=>{if(o)return n(o);i({bytesWritten:s,buffers:a})})})});typeof gr.realpath.native=="function"&&(xo.realpath.native=XI(gr.realpath.native))});var Lb=g((QEe,ZI)=>{ZI.exports=r=>{let e=process.versions.node.split(".").map(t=>parseInt(t,10));return r=r.split(".").map(t=>parseInt(t,10)),e[0]>r[0]||e[0]===r[0]&&(e[1]>r[1]||e[1]===r[1]&&e[2]>=r[2])}});var iF=g((eCe,Mb)=>{"use strict";var za=Sc(),Ln=require("path"),Yee=Lb(),QI=Yee("10.12.0"),eF=r=>{if(process.platform==="win32"&&/[<>:"|?*]/.test(r.replace(Ln.parse(r).root,""))){let t=new Error(`Path contains invalid characters: ${r}`);throw t.code="EINVAL",t}},tF=r=>{let e={mode:511};return typeof r=="number"&&(r={mode:r}),{...e,...r}},rF=r=>{let e=new Error(`operation not permitted, mkdir '${r}'`);return e.code="EPERM",e.errno=-4048,e.path=r,e.syscall="mkdir",e};Mb.exports.makeDir=async(r,e)=>{if(eF(r),e=tF(e),QI){let i=Ln.resolve(r);return za.mkdir(i,{mode:e.mode,recursive:!0})}let t=async i=>{try{await za.mkdir(i,e.mode)}catch(n){if(n.code==="EPERM")throw n;if(n.code==="ENOENT"){if(Ln.dirname(i)===i)throw rF(i);if(n.message.includes("null bytes"))throw n;return await t(Ln.dirname(i)),t(i)}try{if(!(await za.stat(i)).isDirectory())throw new Error("The path is not a directory")}catch{throw n}}};return t(Ln.resolve(r))};Mb.exports.makeDirSync=(r,e)=>{if(eF(r),e=tF(e),QI){let i=Ln.resolve(r);return za.mkdirSync(i,{mode:e.mode,recursive:!0})}let t=i=>{try{za.mkdirSync(i,e.mode)}catch(n){if(n.code==="EPERM")throw n;if(n.code==="ENOENT"){if(Ln.dirname(i)===i)throw rF(i);if(n.message.includes("null bytes"))throw n;return t(Ln.dirname(i)),t(i)}try{if(!za.statSync(i).isDirectory())throw new Error("The path is not a directory")}catch{throw n}}};return t(Ln.resolve(r))}});var qi=g((tCe,nF)=>{"use strict";var Xee=Ur().fromPromise,{makeDir:Zee,makeDirSync:Nb}=iF(),qb=Xee(Zee);nF.exports={mkdirs:qb,mkdirsSync:Nb,mkdirp:qb,mkdirpSync:Nb,ensureDir:qb,ensureDirSync:Nb}});var $b=g((rCe,oF)=>{"use strict";var Ga=Ce();function Qee(r,e,t,i){Ga.open(r,"r+",(n,o)=>{if(n)return i(n);Ga.futimes(o,e,t,s=>{Ga.close(o,a=>{i&&i(s||a)})})})}function ete(r,e,t){let i=Ga.openSync(r,"r+");return Ga.futimesSync(i,e,t),Ga.closeSync(i)}oF.exports={utimesMillis:Qee,utimesMillisSync:ete}});var Ec=g((iCe,sF)=>{"use strict";var Va=Sc(),_r=require("path"),tte=require("util"),rte=Lb(),th=rte("10.5.0"),aF=r=>th?Va.stat(r,{bigint:!0}):Va.stat(r),Bb=r=>th?Va.statSync(r,{bigint:!0}):Va.statSync(r);function ite(r,e){return Promise.all([aF(r),aF(e).catch(t=>{if(t.code==="ENOENT")return null;throw t})]).then(([t,i])=>({srcStat:t,destStat:i}))}function nte(r,e){let t,i=Bb(r);try{t=Bb(e)}catch(n){if(n.code==="ENOENT")return{srcStat:i,destStat:null};throw n}return{srcStat:i,destStat:t}}function ote(r,e,t,i){tte.callbackify(ite)(r,e,(n,o)=>{if(n)return i(n);let{srcStat:s,destStat:a}=o;return a&&rh(s,a)?i(new Error("Source and destination must not be the same.")):s.isDirectory()&&jb(r,e)?i(new Error(ih(r,e,t))):i(null,{srcStat:s,destStat:a})})}function ste(r,e,t){let{srcStat:i,destStat:n}=nte(r,e);if(n&&rh(i,n))throw new Error("Source and destination must not be the same.");if(i.isDirectory()&&jb(r,e))throw new Error(ih(r,e,t));return{srcStat:i,destStat:n}}function lF(r,e,t,i,n){let o=_r.resolve(_r.dirname(r)),s=_r.resolve(_r.dirname(t));if(s===o||s===_r.parse(s).root)return n();let a=(l,u)=>l?l.code==="ENOENT"?n():n(l):rh(e,u)?n(new Error(ih(r,t,i))):lF(r,e,s,i,n);th?Va.stat(s,{bigint:!0},a):Va.stat(s,a)}function uF(r,e,t,i){let n=_r.resolve(_r.dirname(r)),o=_r.resolve(_r.dirname(t));if(o===n||o===_r.parse(o).root)return;let s;try{s=Bb(o)}catch(a){if(a.code==="ENOENT")return;throw a}if(rh(e,s))throw new Error(ih(r,t,i));return uF(r,e,o,i)}function rh(r,e){return!!(e.ino&&e.dev&&e.ino===r.ino&&e.dev===r.dev&&(th||e.inon),i=_r.resolve(e).split(_r.sep).filter(n=>n);return t.reduce((n,o,s)=>n&&i[s]===o,!0)}function ih(r,e,t){return`Cannot ${t} '${r}' to a subdirectory of itself, '${e}'.`}sF.exports={checkPaths:ote,checkPathsSync:ste,checkParentPaths:lF,checkParentPathsSync:uF,isSrcSubdir:jb}});var hF=g((nCe,cF)=>{"use strict";var tr=Ce(),Cc=require("path"),ate=qi().mkdirsSync,lte=$b().utimesMillisSync,_c=Ec();function cte(r,e,t){typeof t=="function"&&(t={filter:t}),t=t||{},t.clobber="clobber"in t?!!t.clobber:!0,t.overwrite="overwrite"in t?!!t.overwrite:t.clobber,t.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`);let{srcStat:i,destStat:n}=_c.checkPathsSync(r,e,"copy");return _c.checkParentPathsSync(r,i,e,"copy"),ute(n,r,e,t)}function ute(r,e,t,i){if(i.filter&&!i.filter(e,t))return;let n=Cc.dirname(t);return tr.existsSync(n)||ate(n),fF(r,e,t,i)}function fF(r,e,t,i){if(!(i.filter&&!i.filter(e,t)))return fte(r,e,t,i)}function fte(r,e,t,i){let o=(i.dereference?tr.statSync:tr.lstatSync)(e);if(o.isDirectory())return dte(o,r,e,t,i);if(o.isFile()||o.isCharacterDevice()||o.isBlockDevice())return pte(o,r,e,t,i);if(o.isSymbolicLink())return hte(r,e,t,i)}function pte(r,e,t,i,n){return e?mte(r,t,i,n):pF(r,t,i,n)}function mte(r,e,t,i){if(i.overwrite)return tr.unlinkSync(t),pF(r,e,t,i);if(i.errorOnExist)throw new Error(`'${t}' already exists`)}function pF(r,e,t,i){return tr.copyFileSync(e,t),i.preserveTimestamps&>e(r.mode,e,t),Ub(t,r.mode)}function gte(r,e,t){return vte(r)&&yte(t,r),bte(e,t)}function vte(r){return(r&128)==0}function yte(r,e){return Ub(r,e|128)}function Ub(r,e){return tr.chmodSync(r,e)}function bte(r,e){let t=tr.statSync(r);return lte(e,t.atime,t.mtime)}function dte(r,e,t,i,n){if(!e)return wte(r.mode,t,i,n);if(e&&!e.isDirectory())throw new Error(`Cannot overwrite non-directory '${i}' with directory '${t}'.`);return dF(t,i,n)}function wte(r,e,t,i){return tr.mkdirSync(t),dF(e,t,i),Ub(t,r)}function dF(r,e,t){tr.readdirSync(r).forEach(i=>xte(i,r,e,t))}function xte(r,e,t,i){let n=Cc.join(e,r),o=Cc.join(t,r),{destStat:s}=_c.checkPathsSync(n,o,"copy");return fF(s,n,o,i)}function hte(r,e,t,i){let n=tr.readlinkSync(e);if(i.dereference&&(n=Cc.resolve(process.cwd(),n)),r){let o;try{o=tr.readlinkSync(t)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return tr.symlinkSync(n,t);throw s}if(i.dereference&&(o=Cc.resolve(process.cwd(),o)),_c.isSrcSubdir(n,o))throw new Error(`Cannot copy '${n}' to a subdirectory of itself, '${o}'.`);if(tr.statSync(t).isDirectory()&&_c.isSrcSubdir(o,n))throw new Error(`Cannot overwrite '${o}' with '${n}'.`);return Dte(n,t)}else return tr.symlinkSync(n,t)}function Dte(r,e){return tr.unlinkSync(e),tr.symlinkSync(r,e)}cF.exports=cte});var Wb=g((oCe,mF)=>{"use strict";mF.exports={copySync:hF()}});var Do=g((sCe,gF)=>{"use strict";var Ste=Ur().fromPromise,vF=Sc();function Ete(r){return vF.access(r).then(()=>!0).catch(()=>!1)}gF.exports={pathExists:Ste(Ete),pathExistsSync:vF.existsSync}});var _F=g((aCe,yF)=>{"use strict";var Pr=Ce(),Pc=require("path"),Cte=qi().mkdirs,_te=Do().pathExists,Pte=$b().utimesMillis,Tc=Ec();function Tte(r,e,t,i){typeof t=="function"&&!i?(i=t,t={}):typeof t=="function"&&(t={filter:t}),i=i||function(){},t=t||{},t.clobber="clobber"in t?!!t.clobber:!0,t.overwrite="overwrite"in t?!!t.overwrite:t.clobber,t.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`),Tc.checkPaths(r,e,"copy",(n,o)=>{if(n)return i(n);let{srcStat:s,destStat:a}=o;Tc.checkParentPaths(r,s,e,"copy",l=>l?i(l):t.filter?wF(bF,a,r,e,t,i):bF(a,r,e,t,i))})}function bF(r,e,t,i,n){let o=Pc.dirname(t);_te(o,(s,a)=>{if(s)return n(s);if(a)return Hb(r,e,t,i,n);Cte(o,l=>l?n(l):Hb(r,e,t,i,n))})}function wF(r,e,t,i,n,o){Promise.resolve(n.filter(t,i)).then(s=>s?r(e,t,i,n,o):o(),s=>o(s))}function Hb(r,e,t,i,n){return i.filter?wF(xF,r,e,t,i,n):xF(r,e,t,i,n)}function xF(r,e,t,i,n){(i.dereference?Pr.stat:Pr.lstat)(e,(s,a)=>{if(s)return n(s);if(a.isDirectory())return kte(a,r,e,t,i,n);if(a.isFile()||a.isCharacterDevice()||a.isBlockDevice())return Rte(a,r,e,t,i,n);if(a.isSymbolicLink())return Ite(r,e,t,i,n)})}function Rte(r,e,t,i,n,o){return e?Fte(r,t,i,n,o):DF(r,t,i,n,o)}function Fte(r,e,t,i,n){if(i.overwrite)Pr.unlink(t,o=>o?n(o):DF(r,e,t,i,n));else return i.errorOnExist?n(new Error(`'${t}' already exists`)):n()}function DF(r,e,t,i,n){Pr.copyFile(e,t,o=>o?n(o):i.preserveTimestamps?Ate(r.mode,e,t,n):nh(t,r.mode,n))}function Ate(r,e,t,i){return Ote(r)?Lte(t,r,n=>n?i(n):SF(r,e,t,i)):SF(r,e,t,i)}function Ote(r){return(r&128)==0}function Lte(r,e,t){return nh(r,e|128,t)}function SF(r,e,t,i){Mte(e,t,n=>n?i(n):nh(t,r,i))}function nh(r,e,t){return Pr.chmod(r,e,t)}function Mte(r,e,t){Pr.stat(r,(i,n)=>i?t(i):Pte(e,n.atime,n.mtime,t))}function kte(r,e,t,i,n,o){return e?e&&!e.isDirectory()?o(new Error(`Cannot overwrite non-directory '${i}' with directory '${t}'.`)):EF(t,i,n,o):Nte(r.mode,t,i,n,o)}function Nte(r,e,t,i,n){Pr.mkdir(t,o=>{if(o)return n(o);EF(e,t,i,s=>s?n(s):nh(t,r,n))})}function EF(r,e,t,i){Pr.readdir(r,(n,o)=>n?i(n):CF(o,r,e,t,i))}function CF(r,e,t,i,n){let o=r.pop();return o?qte(r,o,e,t,i,n):n()}function qte(r,e,t,i,n,o){let s=Pc.join(t,e),a=Pc.join(i,e);Tc.checkPaths(s,a,"copy",(l,u)=>{if(l)return o(l);let{destStat:c}=u;Hb(c,s,a,n,f=>f?o(f):CF(r,t,i,n,o))})}function Ite(r,e,t,i,n){Pr.readlink(e,(o,s)=>{if(o)return n(o);if(i.dereference&&(s=Pc.resolve(process.cwd(),s)),r)Pr.readlink(t,(a,l)=>a?a.code==="EINVAL"||a.code==="UNKNOWN"?Pr.symlink(s,t,n):n(a):(i.dereference&&(l=Pc.resolve(process.cwd(),l)),Tc.isSrcSubdir(s,l)?n(new Error(`Cannot copy '${s}' to a subdirectory of itself, '${l}'.`)):r.isDirectory()&&Tc.isSrcSubdir(l,s)?n(new Error(`Cannot overwrite '${l}' with '${s}'.`)):$te(s,t,n)));else return Pr.symlink(s,t,n)})}function $te(r,e,t){Pr.unlink(e,i=>i?t(i):Pr.symlink(r,e,t))}yF.exports=Tte});var zb=g((lCe,PF)=>{"use strict";var Bte=Ur().fromCallback;PF.exports={copy:Bte(_F())}});var MF=g((uCe,TF)=>{"use strict";var RF=Ce(),kF=require("path"),Ve=require("assert"),Rc=process.platform==="win32";function IF(r){["unlink","chmod","stat","lstat","rmdir","readdir"].forEach(t=>{r[t]=r[t]||RF[t],t=t+"Sync",r[t]=r[t]||RF[t]}),r.maxBusyTries=r.maxBusyTries||3}function Gb(r,e,t){let i=0;typeof e=="function"&&(t=e,e={}),Ve(r,"rimraf: missing path"),Ve.strictEqual(typeof r,"string","rimraf: path should be a string"),Ve.strictEqual(typeof t,"function","rimraf: callback function required"),Ve(e,"rimraf: invalid options argument provided"),Ve.strictEqual(typeof e,"object","rimraf: options should be object"),IF(e),FF(r,e,function n(o){if(o){if((o.code==="EBUSY"||o.code==="ENOTEMPTY"||o.code==="EPERM")&&iFF(r,e,n),s)}o.code==="ENOENT"&&(o=null)}t(o)})}function FF(r,e,t){Ve(r),Ve(e),Ve(typeof t=="function"),e.lstat(r,(i,n)=>{if(i&&i.code==="ENOENT")return t(null);if(i&&i.code==="EPERM"&&Rc)return AF(r,e,i,t);if(n&&n.isDirectory())return oh(r,e,i,t);e.unlink(r,o=>{if(o){if(o.code==="ENOENT")return t(null);if(o.code==="EPERM")return Rc?AF(r,e,o,t):oh(r,e,o,t);if(o.code==="EISDIR")return oh(r,e,o,t)}return t(o)})})}function AF(r,e,t,i){Ve(r),Ve(e),Ve(typeof i=="function"),e.chmod(r,438,n=>{n?i(n.code==="ENOENT"?null:t):e.stat(r,(o,s)=>{o?i(o.code==="ENOENT"?null:t):s.isDirectory()?oh(r,e,t,i):e.unlink(r,i)})})}function OF(r,e,t){let i;Ve(r),Ve(e);try{e.chmodSync(r,438)}catch(n){if(n.code==="ENOENT")return;throw t}try{i=e.statSync(r)}catch(n){if(n.code==="ENOENT")return;throw t}i.isDirectory()?sh(r,e,t):e.unlinkSync(r)}function oh(r,e,t,i){Ve(r),Ve(e),Ve(typeof i=="function"),e.rmdir(r,n=>{n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")?jte(r,e,i):n&&n.code==="ENOTDIR"?i(t):i(n)})}function jte(r,e,t){Ve(r),Ve(e),Ve(typeof t=="function"),e.readdir(r,(i,n)=>{if(i)return t(i);let o=n.length,s;if(o===0)return e.rmdir(r,t);n.forEach(a=>{Gb(kF.join(r,a),e,l=>{if(!s){if(l)return t(s=l);--o==0&&e.rmdir(r,t)}})})})}function LF(r,e){let t;e=e||{},IF(e),Ve(r,"rimraf: missing path"),Ve.strictEqual(typeof r,"string","rimraf: path should be a string"),Ve(e,"rimraf: missing options"),Ve.strictEqual(typeof e,"object","rimraf: options should be object");try{t=e.lstatSync(r)}catch(i){if(i.code==="ENOENT")return;i.code==="EPERM"&&Rc&&OF(r,e,i)}try{t&&t.isDirectory()?sh(r,e,null):e.unlinkSync(r)}catch(i){if(i.code==="ENOENT")return;if(i.code==="EPERM")return Rc?OF(r,e,i):sh(r,e,i);if(i.code!=="EISDIR")throw i;sh(r,e,i)}}function sh(r,e,t){Ve(r),Ve(e);try{e.rmdirSync(r)}catch(i){if(i.code==="ENOTDIR")throw t;if(i.code==="ENOTEMPTY"||i.code==="EEXIST"||i.code==="EPERM")Ute(r,e);else if(i.code!=="ENOENT")throw i}}function Ute(r,e){if(Ve(r),Ve(e),e.readdirSync(r).forEach(t=>LF(kF.join(r,t),e)),Rc){let t=Date.now();do try{return e.rmdirSync(r,e)}catch{}while(Date.now()-t<500)}else return e.rmdirSync(r,e)}TF.exports=Gb;Gb.sync=LF});var kc=g((cCe,NF)=>{"use strict";var Wte=Ur().fromCallback,qF=MF();NF.exports={remove:Wte(qF),removeSync:qF.sync}});var GF=g((fCe,$F)=>{"use strict";var Hte=Ur().fromCallback,BF=Ce(),jF=require("path"),UF=qi(),WF=kc(),HF=Hte(function(e,t){t=t||function(){},BF.readdir(e,(i,n)=>{if(i)return UF.mkdirs(e,t);n=n.map(s=>jF.join(e,s)),o();function o(){let s=n.pop();if(!s)return t();WF.remove(s,a=>{if(a)return t(a);o()})}})});function zF(r){let e;try{e=BF.readdirSync(r)}catch{return UF.mkdirsSync(r)}e.forEach(t=>{t=jF.join(r,t),WF.removeSync(t)})}$F.exports={emptyDirSync:zF,emptydirSync:zF,emptyDir:HF,emptydir:HF}});var YF=g((pCe,VF)=>{"use strict";var zte=Ur().fromCallback,KF=require("path"),So=Ce(),JF=qi();function Gte(r,e){function t(){So.writeFile(r,"",i=>{if(i)return e(i);e()})}So.stat(r,(i,n)=>{if(!i&&n.isFile())return e();let o=KF.dirname(r);So.stat(o,(s,a)=>{if(s)return s.code==="ENOENT"?JF.mkdirs(o,l=>{if(l)return e(l);t()}):e(s);a.isDirectory()?t():So.readdir(o,l=>{if(l)return e(l)})})})}function Vte(r){let e;try{e=So.statSync(r)}catch{}if(e&&e.isFile())return;let t=KF.dirname(r);try{So.statSync(t).isDirectory()||So.readdirSync(t)}catch(i){if(i&&i.code==="ENOENT")JF.mkdirsSync(t);else throw i}So.writeFileSync(r,"")}VF.exports={createFile:zte(Gte),createFileSync:Vte}});var tA=g((dCe,XF)=>{"use strict";var Kte=Ur().fromCallback,ZF=require("path"),As=Ce(),QF=qi(),eA=Do().pathExists;function Jte(r,e,t){function i(n,o){As.link(n,o,s=>{if(s)return t(s);t(null)})}eA(e,(n,o)=>{if(n)return t(n);if(o)return t(null);As.lstat(r,s=>{if(s)return s.message=s.message.replace("lstat","ensureLink"),t(s);let a=ZF.dirname(e);eA(a,(l,u)=>{if(l)return t(l);if(u)return i(r,e);QF.mkdirs(a,c=>{if(c)return t(c);i(r,e)})})})})}function Yte(r,e){if(As.existsSync(e))return;try{As.lstatSync(r)}catch(o){throw o.message=o.message.replace("lstat","ensureLink"),o}let i=ZF.dirname(e);return As.existsSync(i)||QF.mkdirsSync(i),As.linkSync(r,e)}XF.exports={createLink:Kte(Jte),createLinkSync:Yte}});var iA=g((hCe,rA)=>{"use strict";var Eo=require("path"),Ic=Ce(),Xte=Do().pathExists;function Zte(r,e,t){if(Eo.isAbsolute(r))return Ic.lstat(r,i=>i?(i.message=i.message.replace("lstat","ensureSymlink"),t(i)):t(null,{toCwd:r,toDst:r}));{let i=Eo.dirname(e),n=Eo.join(i,r);return Xte(n,(o,s)=>o?t(o):s?t(null,{toCwd:n,toDst:r}):Ic.lstat(r,a=>a?(a.message=a.message.replace("lstat","ensureSymlink"),t(a)):t(null,{toCwd:r,toDst:Eo.relative(i,r)})))}}function Qte(r,e){let t;if(Eo.isAbsolute(r)){if(t=Ic.existsSync(r),!t)throw new Error("absolute srcpath does not exist");return{toCwd:r,toDst:r}}else{let i=Eo.dirname(e),n=Eo.join(i,r);if(t=Ic.existsSync(n),t)return{toCwd:n,toDst:r};if(t=Ic.existsSync(r),!t)throw new Error("relative srcpath does not exist");return{toCwd:r,toDst:Eo.relative(i,r)}}}rA.exports={symlinkPaths:Zte,symlinkPathsSync:Qte}});var sA=g((mCe,nA)=>{"use strict";var oA=Ce();function ere(r,e,t){if(t=typeof e=="function"?e:t,e=typeof e=="function"?!1:e,e)return t(null,e);oA.lstat(r,(i,n)=>{if(i)return t(null,"file");e=n&&n.isDirectory()?"dir":"file",t(null,e)})}function tre(r,e){let t;if(e)return e;try{t=oA.lstatSync(r)}catch{return"file"}return t&&t.isDirectory()?"dir":"file"}nA.exports={symlinkType:ere,symlinkTypeSync:tre}});var dA=g((gCe,aA)=>{"use strict";var rre=Ur().fromCallback,lA=require("path"),Ka=Ce(),uA=qi(),ire=uA.mkdirs,nre=uA.mkdirsSync,cA=iA(),ore=cA.symlinkPaths,sre=cA.symlinkPathsSync,fA=sA(),are=fA.symlinkType,lre=fA.symlinkTypeSync,pA=Do().pathExists;function ure(r,e,t,i){i=typeof t=="function"?t:i,t=typeof t=="function"?!1:t,pA(e,(n,o)=>{if(n)return i(n);if(o)return i(null);ore(r,e,(s,a)=>{if(s)return i(s);r=a.toDst,are(a.toCwd,t,(l,u)=>{if(l)return i(l);let c=lA.dirname(e);pA(c,(f,p)=>{if(f)return i(f);if(p)return Ka.symlink(r,e,u,i);ire(c,d=>{if(d)return i(d);Ka.symlink(r,e,u,i)})})})})})}function cre(r,e,t){if(Ka.existsSync(e))return;let n=sre(r,e);r=n.toDst,t=lre(n.toCwd,t);let o=lA.dirname(e);return Ka.existsSync(o)||nre(o),Ka.symlinkSync(r,e,t)}aA.exports={createSymlink:rre(ure),createSymlinkSync:cre}});var mA=g((vCe,hA)=>{"use strict";var ah=YF(),lh=tA(),uh=dA();hA.exports={createFile:ah.createFile,createFileSync:ah.createFileSync,ensureFile:ah.createFile,ensureFileSync:ah.createFileSync,createLink:lh.createLink,createLinkSync:lh.createLinkSync,ensureLink:lh.createLink,ensureLinkSync:lh.createLinkSync,createSymlink:uh.createSymlink,createSymlinkSync:uh.createSymlinkSync,ensureSymlink:uh.createSymlink,ensureSymlinkSync:uh.createSymlinkSync}});var gA=g(Vb=>{"use strict";Vb.fromCallback=function(r){return Object.defineProperty(function(...e){if(typeof e[e.length-1]=="function")r.apply(this,e);else return new Promise((t,i)=>{r.call(this,...e,(n,o)=>n!=null?i(n):t(o))})},"name",{value:r.name})};Vb.fromPromise=function(r){return Object.defineProperty(function(...e){let t=e[e.length-1];if(typeof t!="function")return r.apply(this,e);r.apply(this,e.slice(0,-1)).then(i=>t(null,i),t)},"name",{value:r.name})}});var ch=g((bCe,vA)=>{function fre(r,{EOL:e=` +`,finalEOL:t=!0,replacer:i=null,spaces:n}={}){let o=t?e:"";return JSON.stringify(r,i,n).replace(/\n/g,e)+o}function pre(r){return Buffer.isBuffer(r)&&(r=r.toString("utf8")),r.replace(/^\uFEFF/,"")}vA.exports={stringify:fre,stripBom:pre}});var xA=g((wCe,yA)=>{var Ja;try{Ja=Ce()}catch(r){Ja=require("fs")}var fh=gA(),{stringify:bA,stripBom:wA}=ch();async function dre(r,e={}){typeof e=="string"&&(e={encoding:e});let t=e.fs||Ja,i="throws"in e?e.throws:!0,n=await fh.fromCallback(t.readFile)(r,e);n=wA(n);let o;try{o=JSON.parse(n,e?e.reviver:null)}catch(s){if(i)throw s.message=`${r}: ${s.message}`,s;return null}return o}var hre=fh.fromPromise(dre);function mre(r,e={}){typeof e=="string"&&(e={encoding:e});let t=e.fs||Ja,i="throws"in e?e.throws:!0;try{let n=t.readFileSync(r,e);return n=wA(n),JSON.parse(n,e.reviver)}catch(n){if(i)throw n.message=`${r}: ${n.message}`,n;return null}}async function gre(r,e,t={}){let i=t.fs||Ja,n=bA(e,t);await fh.fromCallback(i.writeFile)(r,n,t)}var vre=fh.fromPromise(gre);function yre(r,e,t={}){let i=t.fs||Ja,n=bA(e,t);return i.writeFileSync(r,n,t)}var bre={readFile:hre,readFileSync:mre,writeFile:vre,writeFileSync:yre};yA.exports=bre});var SA=g((xCe,DA)=>{"use strict";var ph=xA();DA.exports={readJson:ph.readFile,readJsonSync:ph.readFileSync,writeJson:ph.writeFile,writeJsonSync:ph.writeFileSync}});var dh=g((DCe,EA)=>{"use strict";var wre=Ur().fromCallback,Fc=Ce(),CA=require("path"),_A=qi(),xre=Do().pathExists;function Dre(r,e,t,i){typeof t=="function"&&(i=t,t="utf8");let n=CA.dirname(r);xre(n,(o,s)=>{if(o)return i(o);if(s)return Fc.writeFile(r,e,t,i);_A.mkdirs(n,a=>{if(a)return i(a);Fc.writeFile(r,e,t,i)})})}function Sre(r,...e){let t=CA.dirname(r);if(Fc.existsSync(t))return Fc.writeFileSync(r,...e);_A.mkdirsSync(t),Fc.writeFileSync(r,...e)}EA.exports={outputFile:wre(Dre),outputFileSync:Sre}});var TA=g((SCe,PA)=>{"use strict";var{stringify:Ere}=ch(),{outputFile:Cre}=dh();async function _re(r,e,t={}){let i=Ere(e,t);await Cre(r,i,t)}PA.exports=_re});var kA=g((ECe,RA)=>{"use strict";var{stringify:Pre}=ch(),{outputFileSync:Tre}=dh();function Rre(r,e,t){let i=Pre(e,t);Tre(r,i,t)}RA.exports=Rre});var FA=g((CCe,IA)=>{"use strict";var kre=Ur().fromPromise,vr=SA();vr.outputJson=kre(TA());vr.outputJsonSync=kA();vr.outputJSON=vr.outputJson;vr.outputJSONSync=vr.outputJsonSync;vr.writeJSON=vr.writeJson;vr.writeJSONSync=vr.writeJsonSync;vr.readJSON=vr.readJson;vr.readJSONSync=vr.readJsonSync;IA.exports=vr});var qA=g((_Ce,AA)=>{"use strict";var OA=Ce(),Ire=require("path"),Fre=Wb().copySync,LA=kc().removeSync,Are=qi().mkdirpSync,MA=Ec();function Lre(r,e,t){t=t||{};let i=t.overwrite||t.clobber||!1,{srcStat:n}=MA.checkPathsSync(r,e,"move");return MA.checkParentPathsSync(r,n,e,"move"),Are(Ire.dirname(e)),Ore(r,e,i)}function Ore(r,e,t){if(t)return LA(e),NA(r,e,t);if(OA.existsSync(e))throw new Error("dest already exists.");return NA(r,e,t)}function NA(r,e,t){try{OA.renameSync(r,e)}catch(i){if(i.code!=="EXDEV")throw i;return Mre(r,e,t)}}function Mre(r,e,t){return Fre(r,e,{overwrite:t,errorOnExist:!0}),LA(r)}AA.exports=Lre});var BA=g((PCe,$A)=>{"use strict";$A.exports={moveSync:qA()}});var zA=g((TCe,jA)=>{"use strict";var Nre=Ce(),qre=require("path"),$re=zb().copy,UA=kc().remove,Bre=qi().mkdirp,jre=Do().pathExists,WA=Ec();function Wre(r,e,t,i){typeof t=="function"&&(i=t,t={});let n=t.overwrite||t.clobber||!1;WA.checkPaths(r,e,"move",(o,s)=>{if(o)return i(o);let{srcStat:a}=s;WA.checkParentPaths(r,a,e,"move",l=>{if(l)return i(l);Bre(qre.dirname(e),u=>u?i(u):Ure(r,e,n,i))})})}function Ure(r,e,t,i){if(t)return UA(e,n=>n?i(n):HA(r,e,t,i));jre(e,(n,o)=>n?i(n):o?i(new Error("dest already exists.")):HA(r,e,t,i))}function HA(r,e,t,i){Nre.rename(r,e,n=>n?n.code!=="EXDEV"?i(n):Hre(r,e,t,i):i())}function Hre(r,e,t,i){$re(r,e,{overwrite:t,errorOnExist:!0},o=>o?i(o):UA(r,i))}jA.exports=Wre});var VA=g((RCe,GA)=>{"use strict";var zre=Ur().fromCallback;GA.exports={move:zre(zA())}});var $i=g((kCe,Kb)=>{"use strict";Kb.exports={...Sc(),...Wb(),...zb(),...GF(),...mA(),...FA(),...qi(),...BA(),...VA(),...dh(),...Do(),...kc()};var KA=require("fs");Object.getOwnPropertyDescriptor(KA,"promises")&&Object.defineProperty(Kb.exports,"promises",{get(){return KA.promises}})});var j=g((ICe,JA)=>{var Os=S(require("fs")),Jb=S(Ab()),hh=S(require("path")),YA=S(require("os")),XA=S($i());function Gre(){let r=process.env.NVIM_COC_LOG_FILE;if(r)return r;let e=process.env.XDG_RUNTIME_DIR;if(e)try{return Os.default.accessSync(e,Os.default.constants.R_OK|Os.default.constants.W_OK),hh.default.join(e,`coc-nvim-${process.pid}.log`)}catch(i){}let t=YA.default.tmpdir();return e=hh.default.join(t,`coc.nvim-${process.pid}`),Os.default.existsSync(e)||XA.mkdirpSync(e),hh.default.join(e,"coc-nvim.log")}var Vre=1024*1024,Kre=10,mh=Gre(),Jre=process.env.NVIM_COC_LOG_LEVEL||"info";if(Os.default.existsSync(mh))try{Os.default.writeFileSync(mh,"",{encoding:"utf8",mode:438})}catch(r){}Jb.default.configure({disableClustering:!0,appenders:{out:{type:"file",mode:438,filename:mh,maxLogSize:Vre,backups:Kre,layout:{type:"pattern",pattern:`%d{ISO8601} %p (pid:${process.pid}) [%c] - %m`}}},categories:{default:{appenders:["out"],level:Jre}}});JA.exports=(r="coc-nvim")=>{let e=Jb.default.getLogger(r);return e.getLogFile=()=>mh,e}});var gh=g(()=>{Promise.prototype.logError=function(){this.catch(r=>{j()("extensions").error(r)})}});var QA=g((Yb,ZA)=>{ZA.exports=Xb(typeof Buffer!="undefined"&&Buffer)||Xb(Yb.Buffer)||Xb(typeof window!="undefined"&&window.Buffer)||Yb.Buffer;function Xb(r){return r&&r.isBuffer&&r}});var vh=g((OCe,eO)=>{var Yre={}.toString;eO.exports=Array.isArray||function(r){return Yre.call(r)=="[object Array]"}});var iO=g((Ya,tO)=>{var Xa=Wr(),Ya=tO.exports=rO(0);Ya.alloc=rO;Ya.concat=Xa.concat;Ya.from=Xre;function rO(r){return new Array(r)}function Xre(r){if(!Xa.isBuffer(r)&&Xa.isView(r))r=Xa.Uint8Array.from(r);else if(Xa.isArrayBuffer(r))r=new Uint8Array(r);else{if(typeof r=="string")return Xa.from.call(Ya,r);if(typeof r=="number")throw new TypeError('"value" argument must not be a number')}return Array.prototype.slice.call(r)}});var sO=g((Za,nO)=>{var Mn=Wr(),Qa=Mn.global,Za=nO.exports=Mn.hasBuffer?oO(0):[];Za.alloc=Mn.hasBuffer&&Qa.alloc||oO;Za.concat=Mn.concat;Za.from=Zre;function oO(r){return new Qa(r)}function Zre(r){if(!Mn.isBuffer(r)&&Mn.isView(r))r=Mn.Uint8Array.from(r);else if(Mn.isArrayBuffer(r))r=new Uint8Array(r);else{if(typeof r=="string")return Mn.from.call(Za,r);if(typeof r=="number")throw new TypeError('"value" argument must not be a number')}return Qa.from&&Qa.from.length!==1?Qa.from(r):new Qa(r)}});var uO=g((el,aO)=>{var yh=Wr(),el=aO.exports=yh.hasArrayBuffer?lO(0):[];el.alloc=lO;el.concat=yh.concat;el.from=Qre;function lO(r){return new Uint8Array(r)}function Qre(r){if(yh.isView(r)){var e=r.byteOffset,t=r.byteLength;r=r.buffer,r.byteLength!==t&&(r.slice?r=r.slice(e,e+t):(r=new Uint8Array(r),r.byteLength!==t&&(r=Array.prototype.slice.call(r,e,e+t))))}else{if(typeof r=="string")return yh.from.call(el,r);if(typeof r=="number")throw new TypeError('"value" argument must not be a number')}return new Uint8Array(r)}});var cO=g(bh=>{bh.copy=eie;bh.toString=tie;bh.write=rie;function rie(r,e){for(var t=this,i=e||(e|=0),n=r.length,o=0,s=0;s>>6,t[i++]=128|o&63):o<55296||o>57343?(t[i++]=224|o>>>12,t[i++]=128|o>>>6&63,t[i++]=128|o&63):(o=(o-55296<<10|r.charCodeAt(s++)-56320)+65536,t[i++]=240|o>>>18,t[i++]=128|o>>>12&63,t[i++]=128|o>>>6&63,t[i++]=128|o&63);return i-e}function tie(r,e,t){var i=this,n=e|0;t||(t=i.length);for(var o="",s=0;n=65536?(s-=65536,o+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):o+=String.fromCharCode(s)}return o}function eie(r,e,t,i){var n;t||(t=0),!i&&i!==0&&(i=this.length),e||(e=0);var o=i-t;if(r===this&&t=0;n--)r[n+e]=this[n+t];else for(n=0;n{var Zb=cO();Ac.copy=fO;Ac.slice=pO;Ac.toString=iie;Ac.write=nie("write");var Co=Wr(),dO=Co.global,hO=Co.hasBuffer&&"TYPED_ARRAY_SUPPORT"in dO,mO=hO&&!dO.TYPED_ARRAY_SUPPORT;function fO(r,e,t,i){var n=Co.isBuffer(this),o=Co.isBuffer(r);if(n&&o)return this.copy(r,e,t,i);if(!mO&&!n&&!o&&Co.isView(this)&&Co.isView(r)){var s=t||i!=null?pO.call(this,t,i):this;return r.set(s,e),s.length}else return Zb.copy.call(this,r,e,t,i)}function pO(r,e){var t=this.slice||!mO&&this.subarray;if(t)return t.call(this,r,e);var i=Co.alloc.call(this,e-r);return fO.call(this,i,0,r,e),i}function iie(r,e,t){var i=!hO&&Co.isBuffer(this)?this.toString:Zb.toString;return i.apply(this,arguments)}function nie(r){return e;function e(){var t=this[r]||Zb[r];return t.apply(this,arguments)}}});var Wr=g(rr=>{var Qb=rr.global=QA(),gO=rr.hasBuffer=Qb&&!!Qb.isBuffer,ew=rr.hasArrayBuffer=typeof ArrayBuffer!="undefined",oie=rr.isArray=vh();rr.isArrayBuffer=ew?sie:tw;var aie=rr.isBuffer=gO?Qb.isBuffer:tw,lie=rr.isView=ew?ArrayBuffer.isView||vO("ArrayBuffer","buffer"):tw;rr.alloc=rw;rr.concat=uie;rr.from=cie;var yO=rr.Array=iO(),bO=rr.Buffer=sO(),wO=rr.Uint8Array=uO(),iw=rr.prototype=wh();function cie(r){return typeof r=="string"?fie.call(this,r):xO(this).from(r)}function rw(r){return xO(this).alloc(r)}function uie(r,e){e||(e=0,Array.prototype.forEach.call(r,o));var t=this!==rr&&this||r[0],i=rw.call(t,e),n=0;return Array.prototype.forEach.call(r,s),i;function o(a){e+=a.length}function s(a){n+=iw.copy.call(a,i,n)}}var pie=vO("ArrayBuffer");function sie(r){return r instanceof ArrayBuffer||pie(r)}function fie(r){var e=r.length*3,t=rw.call(this,e),i=iw.write.call(t,r);return e!==i&&(t=iw.slice.call(t,0,i)),t}function xO(r){return aie(r)?bO:lie(r)?wO:oie(r)?yO:gO?bO:ew?wO:yO}function tw(){return!1}function vO(r,e){return r="[object "+r+"]",function(t){return t!=null&&{}.toString.call(e?t[e]:t)===r}}});var xh=g(DO=>{DO.ExtBuffer=nw;var die=Wr();function nw(r,e){if(!(this instanceof nw))return new nw(r,e);this.buffer=die.from(r),this.type=e}});var EO=g(SO=>{SO.setExtPackers=hie;var Dh=Wr(),mie=Dh.global,Bi=Dh.Uint8Array.from,ow,gie={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function hie(r){r.addExtPacker(14,Error,[Ls,mi]),r.addExtPacker(1,EvalError,[Ls,mi]),r.addExtPacker(2,RangeError,[Ls,mi]),r.addExtPacker(3,ReferenceError,[Ls,mi]),r.addExtPacker(4,SyntaxError,[Ls,mi]),r.addExtPacker(5,TypeError,[Ls,mi]),r.addExtPacker(6,URIError,[Ls,mi]),r.addExtPacker(10,RegExp,[vie,mi]),r.addExtPacker(11,Boolean,[sw,mi]),r.addExtPacker(12,String,[sw,mi]),r.addExtPacker(13,Date,[Number,mi]),r.addExtPacker(15,Number,[sw,mi]),typeof Uint8Array!="undefined"&&(r.addExtPacker(17,Int8Array,Bi),r.addExtPacker(18,Uint8Array,Bi),r.addExtPacker(19,Int16Array,Bi),r.addExtPacker(20,Uint16Array,Bi),r.addExtPacker(21,Int32Array,Bi),r.addExtPacker(22,Uint32Array,Bi),r.addExtPacker(23,Float32Array,Bi),typeof Float64Array!="undefined"&&r.addExtPacker(24,Float64Array,Bi),typeof Uint8ClampedArray!="undefined"&&r.addExtPacker(25,Uint8ClampedArray,Bi),r.addExtPacker(26,ArrayBuffer,Bi),r.addExtPacker(29,DataView,Bi)),Dh.hasBuffer&&r.addExtPacker(27,mie,Dh.from)}function mi(r){return ow||(ow=aw().encode),ow(r)}function sw(r){return r.valueOf()}function vie(r){r=RegExp.prototype.toString.call(r).split("/"),r.shift();var e=[r.pop()];return e.unshift(r.join("/")),e}function Ls(r){var e={};for(var t in gie)e[t]=r[t];return e}});var Sh=g(Oc=>{var yie,bie,wie,xie;(function(r){var e="undefined",t=e!==typeof Buffer&&Buffer,i=e!==typeof Uint8Array&&Uint8Array,n=e!==typeof ArrayBuffer&&ArrayBuffer,o=[0,0,0,0,0,0,0,0],s=Array.isArray||P,a=4294967296,l=16777216,u;yie=c("Uint64BE",!0,!0),bie=c("Int64BE",!0,!1),wie=c("Uint64LE",!1,!0),xie=c("Int64LE",!1,!1);function c(k,_,O){var I=_?0:4,L=_?4:0,R=_?0:3,F=_?1:2,q=_?2:1,K=_?3:0,ae=_?v:w,Pe=_?x:E,We=dr.prototype,Yt="is"+k,Nt="_"+Yt;return We.buffer=void 0,We.offset=0,We[Nt]=!0,We.toNumber=Dd,We.toString=_y,We.toJSON=Dd,We.toArray=f,t&&(We.toBuffer=p),i&&(We.toArrayBuffer=d),dr[Yt]=kn,r[k]=dr,dr;function dr(Se,ve,fe,Ee){return this instanceof dr?In(this,Se,ve,fe,Ee):new dr(Se,ve,fe,Ee)}function kn(Se){return!!(Se&&Se[Nt])}function In(Se,ve,fe,Ee,Ct){if(i&&n&&(ve instanceof n&&(ve=new i(ve)),Ee instanceof n&&(Ee=new i(Ee))),!ve&&!fe&&!Ee&&!u){Se.buffer=y(o,0);return}if(!h(ve,fe)){var Oi=u||Array;Ct=fe,Ee=ve,fe=0,ve=new Oi(8)}Se.buffer=ve,Se.offset=fe|=0,e!==typeof Ee&&(typeof Ee=="string"?Cy(ve,fe,Ee,Ct||10):h(Ee,Ct)?m(ve,fe,Ee,Ct):typeof Ct=="number"?(Fa(ve,fe+I,Ee),Fa(ve,fe+L,Ct)):Ee>0?ae(ve,fe,Ee):Ee<0?Pe(ve,fe,Ee):m(ve,fe,o,0))}function Cy(Se,ve,fe,Ee){var Ct=0,Oi=fe.length,Xt=0,qt=0;fe[0]==="-"&&Ct++;for(var Py=Ct;Ct=0))break;qt=qt*Ee+Sd,Xt=Xt*Ee+Math.floor(qt/a),qt%=a}Py&&(Xt=~Xt,qt?qt=a-qt:Xt++),Fa(Se,ve+I,Xt),Fa(Se,ve+L,qt)}function Dd(){var Se=this.buffer,ve=this.offset,fe=Aa(Se,ve+I),Ee=Aa(Se,ve+L);return O||(fe|=0),fe?fe*a+Ee:Ee}function _y(Se){var ve=this.buffer,fe=this.offset,Ee=Aa(ve,fe+I),Ct=Aa(ve,fe+L),Oi="",Xt=!O&&Ee&2147483648;for(Xt&&(Ee=~Ee,Ct=a-Ct),Se=Se||10;;){var qt=Ee%Se*a+Ct;if(Ee=Math.floor(Ee/Se),Ct=Math.floor(qt/Se),Oi=(qt%Se).toString(Se)+Oi,!Ee&&!Ct)break}return Xt&&(Oi="-"+Oi),Oi}function Fa(Se,ve,fe){Se[ve+K]=fe&255,fe=fe>>8,Se[ve+q]=fe&255,fe=fe>>8,Se[ve+F]=fe&255,fe=fe>>8,Se[ve+R]=fe&255}function Aa(Se,ve){return Se[ve+R]*l+(Se[ve+F]<<16)+(Se[ve+q]<<8)+Se[ve+K]}}function f(k){var _=this.buffer,O=this.offset;return u=null,k!==!1&&O===0&&_.length===8&&s(_)?_:y(_,O)}function p(k){var _=this.buffer,O=this.offset;if(u=t,k!==!1&&O===0&&_.length===8&&Buffer.isBuffer(_))return _;var I=new t(8);return m(I,0,_,O),I}function d(k){var _=this.buffer,O=this.offset,I=_.buffer;if(u=i,k!==!1&&O===0&&I instanceof n&&I.byteLength===8)return I;var L=new i(8);return m(L,0,_,O),L.buffer}function h(k,_){var O=k&&k.length;return _|=0,O&&_+8<=O&&typeof k[_]!="string"}function m(k,_,O,I){_|=0,I|=0;for(var L=0;L<8;L++)k[_++]=O[I++]&255}function y(k,_){return Array.prototype.slice.call(k,_,_+8)}function v(k,_,O){for(var I=_+8;I>_;)k[--I]=O&255,O/=256}function x(k,_,O){var I=_+8;for(O++;I>_;)k[--I]=-O&255^255,O/=256}function w(k,_,O){for(var I=_+8;_{lw.read=function(r,e,t,i,n){var o,s,a=n*8-i-1,l=(1<>1,c=-7,f=t?n-1:0,p=t?-1:1,d=r[e+f];for(f+=p,o=d&(1<<-c)-1,d>>=-c,c+=a;c>0;o=o*256+r[e+f],f+=p,c-=8);for(s=o&(1<<-c)-1,o>>=-c,c+=i;c>0;s=s*256+r[e+f],f+=p,c-=8);if(o===0)o=1-u;else{if(o===l)return s?NaN:(d?-1:1)*Infinity;s=s+Math.pow(2,i),o=o-u}return(d?-1:1)*s*Math.pow(2,o-i)};lw.write=function(r,e,t,i,n,o){var s,a,l,u=o*8-n-1,c=(1<>1,p=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,h=i?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===Infinity?(a=isNaN(e)?1:0,s=c):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+f>=1?e+=p/l:e+=p*Math.pow(2,1-f),e*l>=2&&(s++,l/=2),s+f>=c?(a=0,s=c):s+f>=1?(a=(e*l-1)*Math.pow(2,n),s=s+f):(a=e*Math.pow(2,f-1)*Math.pow(2,n),s=0));n>=8;r[t+d]=a&255,d+=h,a/=256,n-=8);for(s=s<0;r[t+d]=s&255,d+=h,s/=256,u-=8);r[t+d-h]|=m*128}});var cw=g(CO=>{var Die=CO.uint8=new Array(256);for(var Eh=0;Eh<=255;Eh++)Die[Eh]=Sie(Eh);function Sie(r){return function(e){var t=e.reserve(1);e.buffer[t]=r}}});var MO=g(_O=>{var PO=uw(),TO=Sh(),Eie=TO.Uint64BE,Cie=TO.Int64BE,RO=cw().uint8,Ch=Wr(),nt=Ch.global,_ie=Ch.hasBuffer&&"TYPED_ARRAY_SUPPORT"in nt,Pie=_ie&&!nt.TYPED_ARRAY_SUPPORT,kO=Ch.hasBuffer&&nt.prototype||{};_O.getWriteToken=Tie;function Tie(r){return r&&r.uint8array?Rie():Pie||Ch.hasBuffer&&r&&r.safe?kie():IO()}function Rie(){var r=IO();return r[202]=Be(202,4,FO),r[203]=Be(203,8,AO),r}function IO(){var r=RO.slice();return r[196]=Lc(196),r[197]=Ms(197),r[198]=Ns(198),r[199]=Lc(199),r[200]=Ms(200),r[201]=Ns(201),r[202]=Be(202,4,kO.writeFloatBE||FO,!0),r[203]=Be(203,8,kO.writeDoubleBE||AO,!0),r[204]=Lc(204),r[205]=Ms(205),r[206]=Ns(206),r[207]=Be(207,8,OO),r[208]=Lc(208),r[209]=Ms(209),r[210]=Ns(210),r[211]=Be(211,8,LO),r[217]=Lc(217),r[218]=Ms(218),r[219]=Ns(219),r[220]=Ms(220),r[221]=Ns(221),r[222]=Ms(222),r[223]=Ns(223),r}function kie(){var r=RO.slice();return r[196]=Be(196,1,nt.prototype.writeUInt8),r[197]=Be(197,2,nt.prototype.writeUInt16BE),r[198]=Be(198,4,nt.prototype.writeUInt32BE),r[199]=Be(199,1,nt.prototype.writeUInt8),r[200]=Be(200,2,nt.prototype.writeUInt16BE),r[201]=Be(201,4,nt.prototype.writeUInt32BE),r[202]=Be(202,4,nt.prototype.writeFloatBE),r[203]=Be(203,8,nt.prototype.writeDoubleBE),r[204]=Be(204,1,nt.prototype.writeUInt8),r[205]=Be(205,2,nt.prototype.writeUInt16BE),r[206]=Be(206,4,nt.prototype.writeUInt32BE),r[207]=Be(207,8,OO),r[208]=Be(208,1,nt.prototype.writeInt8),r[209]=Be(209,2,nt.prototype.writeInt16BE),r[210]=Be(210,4,nt.prototype.writeInt32BE),r[211]=Be(211,8,LO),r[217]=Be(217,1,nt.prototype.writeUInt8),r[218]=Be(218,2,nt.prototype.writeUInt16BE),r[219]=Be(219,4,nt.prototype.writeUInt32BE),r[220]=Be(220,2,nt.prototype.writeUInt16BE),r[221]=Be(221,4,nt.prototype.writeUInt32BE),r[222]=Be(222,2,nt.prototype.writeUInt16BE),r[223]=Be(223,4,nt.prototype.writeUInt32BE),r}function Lc(r){return function(e,t){var i=e.reserve(2),n=e.buffer;n[i++]=r,n[i]=t}}function Ms(r){return function(e,t){var i=e.reserve(3),n=e.buffer;n[i++]=r,n[i++]=t>>>8,n[i]=t}}function Ns(r){return function(e,t){var i=e.reserve(5),n=e.buffer;n[i++]=r,n[i++]=t>>>24,n[i++]=t>>>16,n[i++]=t>>>8,n[i]=t}}function Be(r,e,t,i){return function(n,o){var s=n.reserve(e+1);n.buffer[s++]=r,t.call(n.buffer,o,s,i)}}function OO(r,e){new Eie(this,e,r)}function LO(r,e){new Cie(this,e,r)}function FO(r,e){PO.write(this,r,e,!1,23,4)}function AO(r,e){PO.write(this,r,e,!1,52,8)}});var jO=g(NO=>{var Iie=vh(),qO=Sh(),Fie=qO.Uint64BE,Aie=qO.Int64BE,$O=Wr(),BO=wh(),Oie=MO(),Lie=cw().uint8,Mie=xh().ExtBuffer,Nie=typeof Uint8Array!="undefined",qie=typeof Map!="undefined",tl=[];tl[1]=212;tl[2]=213;tl[4]=214;tl[8]=215;tl[16]=216;NO.getWriteType=$ie;function $ie(r){var e=Oie.getWriteToken(r),t=r&&r.useraw,i=Nie&&r&&r.binarraybuffer,n=i?$O.isArrayBuffer:$O.isBuffer,o=i?P:E,s=qie&&r&&r.usemap,a=s?O:_,l={boolean:u,function:x,number:c,object:t?v:y,string:m(t?h:d),symbol:x,undefined:x};return l;function u(L,R){var F=R?195:194;e[F](L,R)}function c(L,R){var F=R|0,q;if(R!==F){q=203,e[q](L,R);return}else-32<=F&&F<=127?q=F&255:0<=F?q=F<=255?204:F<=65535?205:206:q=-128<=F?208:-32768<=F?209:210;e[q](L,F)}function f(L,R){var F=207;e[F](L,R.toArray())}function p(L,R){var F=211;e[F](L,R.toArray())}function d(L){return L<32?1:L<=255?2:L<=65535?3:5}function h(L){return L<32?1:L<=65535?3:5}function m(L){return R;function R(F,q){var K=q.length,ae=5+K*3;F.offset=F.reserve(ae);var Pe=F.buffer,We=L(K),Yt=F.offset+We;K=BO.write.call(Pe,q,Yt);var Nt=L(K);if(We!==Nt){var dr=Yt+Nt-We,kn=Yt+K;BO.copy.call(Pe,Pe,dr,Yt,kn)}var In=Nt===1?160+K:Nt<=3?215+Nt:219;e[In](F,K),F.offset+=K}}function y(L,R){if(R===null)return x(L,R);if(n(R))return o(L,R);if(Iie(R))return w(L,R);if(Fie.isUint64BE(R))return f(L,R);if(Aie.isInt64BE(R))return p(L,R);var F=L.codec.getExtPacker(R);if(F&&(R=F(R)),R instanceof Mie)return k(L,R);a(L,R)}function v(L,R){if(n(R))return I(L,R);y(L,R)}function x(L,R){var F=192;e[F](L,R)}function w(L,R){var F=R.length,q=F<16?144+F:F<=65535?220:221;e[q](L,F);for(var K=L.codec.encode,ae=0;ae{var Bie=vh();Mc.createCodec=UO;Mc.install=jie;Mc.filter=Uie;var Wie=Wr();function rl(r){if(!(this instanceof rl))return new rl(r);this.options=r,this.init()}rl.prototype.init=function(){var r=this.options;return r&&r.uint8array&&(this.bufferish=Wie.Uint8Array),this};function jie(r){for(var e in r)rl.prototype[e]=Hie(rl.prototype[e],r[e])}function Hie(r,e){return r&&e?t:r||e;function t(){return r.apply(this,arguments),e.apply(this,arguments)}}function zie(r){return r=r.slice(),function(t){return r.reduce(e,t)};function e(t,i){return i(t)}}function Uie(r){return Bie(r)?zie(r):r}function UO(r){return new rl(r)}Mc.preset=UO({preset:!0})});var _h=g(WO=>{var Gie=xh().ExtBuffer,Vie=EO(),Kie=jO(),fw=Nc();fw.install({addExtPacker:Jie,getExtPacker:Yie,init:HO});WO.preset=HO.call(fw.preset);function Xie(r){var e=Kie.getWriteType(r);return t;function t(i,n){var o=e[typeof n];if(!o)throw new Error('Unsupported type "'+typeof n+'": '+n);o(i,n)}}function HO(){var r=this.options;return this.encode=Xie(r),r&&r.preset&&Vie.setExtPackers(this),this}function Jie(r,e,t){t=fw.filter(t);var i=e.name;if(i&&i!=="Object"){var n=this.extPackers||(this.extPackers={});n[i]=s}else{var o=this.extEncoderList||(this.extEncoderList=[]);o.unshift([e,s])}function s(a){return t&&(a=t(a)),new Gie(a,r)}}function Yie(r){var e=this.extPackers||(this.extPackers={}),t=r.constructor,i=t&&t.name&&e[t.name];if(i)return i;for(var n=this.extEncoderList||(this.extEncoderList=[]),o=n.length,s=0;s{pw.FlexDecoder=il;pw.FlexEncoder=nl;var qc=Wr(),Zie=2048,Qie=65536,zO="BUFFER_SHORTAGE";function il(){if(!(this instanceof il))return new il}function nl(){if(!(this instanceof nl))return new nl}il.mixin=GO(ene());il.mixin(il.prototype);nl.mixin=GO(tne());nl.mixin(nl.prototype);function ene(){return{bufferish:qc,write:r,fetch:rne,flush:e,push:KO,pull:ine,read:VO,reserve:t,offset:0};function r(i){var n=this.offset?qc.prototype.slice.call(this.buffer,this.offset):this.buffer;this.buffer=n?i?this.bufferish.concat([n,i]):n:i,this.offset=0}function e(){for(;this.offsetthis.buffer.length)throw new Error(zO);return this.offset=o,n}}function tne(){return{bufferish:qc,write:nne,fetch:r,flush:e,push:KO,pull:t,read:VO,reserve:i,send:n,maxBufferSize:Qie,minBufferSize:Zie,offset:0,start:0};function r(){var o=this.start;if(o1?this.bufferish.concat(o):o[0];return o.length=0,s}function i(o){var s=o|0;if(this.buffer){var a=this.buffer.length,l=this.offset|0,u=l+s;if(uthis.minBufferSize)this.flush(),this.push(o);else{var a=this.reserve(s);qc.prototype.copy.call(o,this.buffer,a)}}}function nne(){throw new Error("method not implemented: write()")}function rne(){throw new Error("method not implemented: fetch()")}function VO(){var r=this.buffers&&this.buffers.length;return r?(this.flush(),this.pull()):this.fetch()}function KO(r){var e=this.buffers||(this.buffers=[]);e.push(r)}function ine(){var r=this.buffers||(this.buffers=[]);return r.shift()}function GO(r){return e;function e(t){for(var i in r)t[i]=r[i];return t}}});var Ph=g(JO=>{JO.EncodeBuffer=ol;var one=_h().preset,sne=dw().FlexEncoder;sne.mixin(ol.prototype);function ol(r){if(!(this instanceof ol))return new ol(r);if(r&&(this.options=r,r.codec)){var e=this.codec=r.codec;e.bufferish&&(this.bufferish=e.bufferish)}}ol.prototype.codec=one;ol.prototype.write=function(r){this.codec.encode(this,r)}});var aw=g(YO=>{YO.encode=ane;var lne=Ph().EncodeBuffer;function ane(r,e){var t=new lne(e);return t.write(r),t.read()}});var QO=g(XO=>{XO.setExtUnpackers=une;var ZO=Wr(),cne=ZO.global,hw,fne={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function une(r){r.addExtUnpacker(14,[gi,qs(Error)]),r.addExtUnpacker(1,[gi,qs(EvalError)]),r.addExtUnpacker(2,[gi,qs(RangeError)]),r.addExtUnpacker(3,[gi,qs(ReferenceError)]),r.addExtUnpacker(4,[gi,qs(SyntaxError)]),r.addExtUnpacker(5,[gi,qs(TypeError)]),r.addExtUnpacker(6,[gi,qs(URIError)]),r.addExtUnpacker(10,[gi,pne]),r.addExtUnpacker(11,[gi,yr(Boolean)]),r.addExtUnpacker(12,[gi,yr(String)]),r.addExtUnpacker(13,[gi,yr(Date)]),r.addExtUnpacker(15,[gi,yr(Number)]),typeof Uint8Array!="undefined"&&(r.addExtUnpacker(17,yr(Int8Array)),r.addExtUnpacker(18,yr(Uint8Array)),r.addExtUnpacker(19,[_o,yr(Int16Array)]),r.addExtUnpacker(20,[_o,yr(Uint16Array)]),r.addExtUnpacker(21,[_o,yr(Int32Array)]),r.addExtUnpacker(22,[_o,yr(Uint32Array)]),r.addExtUnpacker(23,[_o,yr(Float32Array)]),typeof Float64Array!="undefined"&&r.addExtUnpacker(24,[_o,yr(Float64Array)]),typeof Uint8ClampedArray!="undefined"&&r.addExtUnpacker(25,yr(Uint8ClampedArray)),r.addExtUnpacker(26,_o),r.addExtUnpacker(29,[_o,yr(DataView)])),ZO.hasBuffer&&r.addExtUnpacker(27,yr(cne))}function gi(r){return hw||(hw=mw().decode),hw(r)}function pne(r){return RegExp.apply(null,r)}function qs(r){return function(e){var t=new r;for(var i in fne)t[i]=e[i];return t}}function yr(r){return function(e){return new r(e)}}function _o(r){return new Uint8Array(r).buffer}});var yw=g(gw=>{var eL=uw(),tL=Sh(),rL=tL.Uint64BE,iL=tL.Int64BE;gw.getReadFormat=dne;gw.readUint8=nL;var vw=Wr(),Th=wh(),hne=typeof Map!="undefined",mne=!0;function dne(r){var e=vw.hasArrayBuffer&&r&&r.binarraybuffer,t=r&&r.int64,i=hne&&r&&r.usemap,n={map:i?vne:gne,array:yne,str:bne,bin:e?xne:wne,ext:Dne,uint8:nL,uint16:Ene,uint32:_ne,uint64:Rh(8,t?kne:Tne),int8:Sne,int16:Cne,int32:Pne,int64:Rh(8,t?Ine:Rne),float32:Rh(4,Fne),float64:Rh(8,Ane)};return n}function gne(r,e){var t={},i,n=new Array(e),o=new Array(e),s=r.codec.decode;for(i=0;i{var One=yw();oL.getReadToken=Lne;function Lne(r){var e=One.getReadFormat(r);return r&&r.useraw?Mne(e):sL(e)}function sL(r){var e,t=new Array(256);for(e=0;e<=127;e++)t[e]=$c(e);for(e=128;e<=143;e++)t[e]=Nn(e-128,r.map);for(e=144;e<=159;e++)t[e]=Nn(e-144,r.array);for(e=160;e<=191;e++)t[e]=Nn(e-160,r.str);for(t[192]=$c(null),t[193]=null,t[194]=$c(!1),t[195]=$c(!0),t[196]=Hr(r.uint8,r.bin),t[197]=Hr(r.uint16,r.bin),t[198]=Hr(r.uint32,r.bin),t[199]=Hr(r.uint8,r.ext),t[200]=Hr(r.uint16,r.ext),t[201]=Hr(r.uint32,r.ext),t[202]=r.float32,t[203]=r.float64,t[204]=r.uint8,t[205]=r.uint16,t[206]=r.uint32,t[207]=r.uint64,t[208]=r.int8,t[209]=r.int16,t[210]=r.int32,t[211]=r.int64,t[212]=Nn(1,r.ext),t[213]=Nn(2,r.ext),t[214]=Nn(4,r.ext),t[215]=Nn(8,r.ext),t[216]=Nn(16,r.ext),t[217]=Hr(r.uint8,r.str),t[218]=Hr(r.uint16,r.str),t[219]=Hr(r.uint32,r.str),t[220]=Hr(r.uint16,r.array),t[221]=Hr(r.uint32,r.array),t[222]=Hr(r.uint16,r.map),t[223]=Hr(r.uint32,r.map),e=224;e<=255;e++)t[e]=$c(e-256);return t}function Mne(r){var e,t=sL(r).slice();for(t[217]=t[196],t[218]=t[197],t[219]=t[198],e=160;e<=191;e++)t[e]=Nn(e-160,r.bin);return t}function $c(r){return function(){return r}}function Hr(r,e){return function(t){var i=r(t);return e(t,i)}}function Nn(r,e){return function(t){return e(t,r)}}});var kh=g(lL=>{var Nne=xh().ExtBuffer,qne=QO(),$ne=yw().readUint8,Bne=aL(),bw=Nc();bw.install({addExtUnpacker:jne,getExtUnpacker:Une,init:uL});lL.preset=uL.call(bw.preset);function Wne(r){var e=Bne.getReadToken(r);return t;function t(i){var n=$ne(i),o=e[n];if(!o)throw new Error("Invalid type: "+(n&&"0x"+n.toString(16)));return o(i)}}function uL(){var r=this.options;return this.decode=Wne(r),r&&r.preset&&qne.setExtUnpackers(this),this}function jne(r,e){var t=this.extUnpackers||(this.extUnpackers=[]);t[r]=bw.filter(e)}function Une(r){var e=this.extUnpackers||(this.extUnpackers=[]);return e[r]||t;function t(i){return new Nne(i,r)}}});var Ih=g(cL=>{cL.DecodeBuffer=sl;var Hne=kh().preset,zne=dw().FlexDecoder;zne.mixin(sl.prototype);function sl(r){if(!(this instanceof sl))return new sl(r);if(r&&(this.options=r,r.codec)){var e=this.codec=r.codec;e.bufferish&&(this.bufferish=e.bufferish)}}sl.prototype.codec=Hne;sl.prototype.fetch=function(){return this.codec.decode(this)}});var mw=g(fL=>{fL.decode=Gne;var Vne=Ih().DecodeBuffer;function Gne(r,e){var t=new Vne(e);return t.write(r),t.read()}});var Dw=g((r_e,ww)=>{function xw(){if(!(this instanceof xw))return new xw}(function(r){typeof ww!="undefined"&&(ww.exports=r);var e="listeners",t={on:n,once:o,off:s,emit:a};i(r.prototype),r.mixin=i;function i(u){for(var c in t)u[c]=t[c];return u}function n(u,c){return l(this,u).push(c),this}function o(u,c){var f=this;return p.originalListener=c,l(f,u).push(p),f;function p(){s.call(f,u,p),c.apply(this,arguments)}}function s(u,c){var f=this,p;if(!arguments.length)delete f[e];else if(c){if(p=l(f,u,!0),p){if(p=p.filter(d),!p.length)return s.call(f,u);f[e][u]=p}}else if(p=f[e],p&&(delete p[u],!Object.keys(p).length))return s.call(f);return f;function d(h){return h!==c&&h.originalListener!==c}}function a(u,c){var f=this,p=l(f,u,!0);if(!p)return!1;var d=arguments.length;if(d===1)p.forEach(m);else if(d===2)p.forEach(y);else{var h=Array.prototype.slice.call(arguments,1);p.forEach(v)}return!!p.length;function m(x){x.call(f)}function y(x){x.call(f,c)}function v(x){x.apply(f,h)}}function l(u,c,f){if(!(f&&!u[e])){var p=u[e]||(u[e]={});return p[c]||(p[c]=[])}}})(xw)});var hL=g(pL=>{pL.Encoder=$s;var Kne=Dw(),dL=Ph().EncodeBuffer;function $s(r){if(!(this instanceof $s))return new $s(r);dL.call(this,r)}$s.prototype=new dL;Kne.mixin($s.prototype);$s.prototype.encode=function(r){this.write(r),this.emit("data",this.read())};$s.prototype.end=function(r){arguments.length&&this.encode(r),this.flush(),this.emit("end")}});var vL=g(mL=>{mL.Decoder=Po;var Jne=Dw(),gL=Ih().DecodeBuffer;function Po(r){if(!(this instanceof Po))return new Po(r);gL.call(this,r)}Po.prototype=new gL;Jne.mixin(Po.prototype);Po.prototype.decode=function(r){arguments.length&&this.write(r),this.flush()};Po.prototype.push=function(r){this.emit("data",r)};Po.prototype.end=function(r){this.decode(r),this.emit("end")}});var wL=g(yL=>{yL.createEncodeStream=al;var Yne=require("util"),bL=require("stream").Transform,Xne=Ph().EncodeBuffer;Yne.inherits(al,bL);var Zne={objectMode:!0};function al(r){if(!(this instanceof al))return new al(r);r?r.objectMode=!0:r=Zne,bL.call(this,r);var e=this,t=this.encoder=new Xne(r);t.push=function(i){e.push(i)}}al.prototype._transform=function(r,e,t){this.encoder.write(r),t&&t()};al.prototype._flush=function(r){this.encoder.flush(),r&&r()}});var SL=g(xL=>{xL.createDecodeStream=Bc;var Qne=require("util"),DL=require("stream").Transform,eoe=Ih().DecodeBuffer;Qne.inherits(Bc,DL);var toe={objectMode:!0};function Bc(r){if(!(this instanceof Bc))return new Bc(r);r?r.objectMode=!0:r=toe,DL.call(this,r);var e=this,t=this.decoder=new eoe(r);t.push=function(i){e.push(i)}}Bc.prototype._transform=function(r,e,t){this.decoder.write(r),this.decoder.flush(),t&&t()}});var CL=g(EL=>{kh();_h();EL.createCodec=Nc().createCodec});var PL=g(_L=>{kh();_h();_L.codec={preset:Nc().preset}});var TL=g(qn=>{qn.encode=aw().encode;qn.decode=mw().decode;qn.Encoder=hL().Encoder;qn.Decoder=vL().Decoder;qn.createEncodeStream=wL().createEncodeStream;qn.createDecodeStream=SL().createDecodeStream;qn.createCodec=CL().createCodec;qn.codec=PL().codec});var kL=g(Sw=>{"use strict";Object.defineProperty(Sw,"__esModule",{value:!0});var roe=require("stream"),RL=class extends roe.Transform{constructor(){super({readableHighWaterMark:10*1024*1024,writableHighWaterMark:10*1024*1024});this.chunks=null,this.timer=null}sendData(){let{chunks:e}=this;if(e){this.chunks=null;let t=Buffer.concat(e);this.push(t)}}_transform(e,t,i){let{chunks:n,timer:o}=this,s=Buffer.poolSize;if(o&&clearTimeout(o),e.length{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});Fh.BaseApi=void 0;var ioe=require("events"),noe=process.env.VIM_NODE_RPC=="1",IL=class extends ioe.EventEmitter{constructor({transport:e,data:t,client:i}){super();this.setTransport(e),this.data=t,this.client=i}setTransport(e){this.transport=e}equals(e){try{return String(this.data)===String(e.data)}catch(t){return!1}}async request(e,t=[]){let i=Error().stack;return new Promise((n,o)=>{this.transport.request(e,this.getArgsByPrefix(t),(s,a)=>{if(s){let l=new Error(`request error ${e} - ${s[1]}`);l.stack=i,e.endsWith("get_var")||this.client.logError(`request error on "${e}"`,t,s[1],i),o(l)}else n(a)})})}getArgsByPrefix(e){return this.prefix!=="nvim_"&&e[0]!=this?[noe?this.data:this,...e]:e}getVar(e){return this.request(`${this.prefix}get_var`,[e]).then(t=>t,t=>null)}setVar(e,t,i=!1){if(i){this.notify(`${this.prefix}set_var`,[e,t]);return}return this.request(`${this.prefix}set_var`,[e,t])}deleteVar(e){this.notify(`${this.prefix}del_var`,[e])}getOption(e){return this.request(`${this.prefix}get_option`,[e])}setOption(e,t,i){if(i){this.notify(`${this.prefix}set_option`,[e,t]);return}return this.request(`${this.prefix}set_option`,[e,t])}notify(e,t=[]){this.transport.notify(e,this.getArgsByPrefix(t))}};Fh.BaseApi=IL});var Uc=g(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});Ah.Buffer=void 0;var ooe=jc(),FL=class extends ooe.BaseApi{constructor(){super(...arguments);this.prefix="nvim_buf_"}async attach(e=!1,t={}){return await this.request(`${this.prefix}attach`,[e,t])}async detach(){return await this.request(`${this.prefix}detach`,[])}get id(){return this.data}get length(){return this.request(`${this.prefix}line_count`,[])}get lines(){return this.getLines()}get changedtick(){return this.request(`${this.prefix}get_changedtick`,[])}get commands(){return this.getCommands()}getCommands(e={}){return this.request(`${this.prefix}get_commands`,[e])}getLines({start:e,end:t,strictIndexing:i}={start:0,end:-1,strictIndexing:!0}){let n=typeof i=="undefined"?!0:i;return this.request(`${this.prefix}get_lines`,[e,t,n])}setLines(e,{start:t,end:i,strictIndexing:n}={strictIndexing:!0},o=!1){let s=typeof n=="undefined"?!0:n,a=typeof e=="string"?[e]:e,l=typeof i!="undefined"?i:t+1;return this[o?"notify":"request"](`${this.prefix}set_lines`,[t,l,s,a])}setVirtualText(e,t,i,n={}){return this.notify(`${this.prefix}set_virtual_text`,[e,t,i,n]),Promise.resolve(e)}insert(e,t){return this.setLines(e,{start:t,end:t,strictIndexing:!0})}replace(e,t){let i=typeof e=="string"?[e]:e;return this.setLines(i,{start:t,end:t+i.length,strictIndexing:!1})}remove(e,t,i=!1){return this.setLines([],{start:e,end:t,strictIndexing:i})}append(e){return this.setLines(e,{start:-1,end:-1,strictIndexing:!1})}get name(){return this.request(`${this.prefix}get_name`,[])}setName(e){return this.request(`${this.prefix}set_name`,[e])}get valid(){return this.request(`${this.prefix}is_valid`,[])}mark(e){return this.request(`${this.prefix}get_mark`,[e])}getKeymap(e){return this.request(`${this.prefix}get_keymap`,[e])}get loaded(){return this.request(`${this.prefix}is_loaded`,[])}getOffset(e){return this.request(`${this.prefix}get_offset`,[e])}addHighlight({hlGroup:e,line:t,colStart:i,colEnd:n,srcId:o}){if(!e)throw new Error("hlGroup should not empty");let s=typeof n!="undefined"?n:-1,a=typeof i!="undefined"?i:-0,l=typeof o!="undefined"?o:-1,u=l==0?"request":"notify",c=this[u](`${this.prefix}add_highlight`,[l,e,t,a,s]);return u==="request"?c:Promise.resolve(null)}clearHighlight(e={}){let t={srcId:-1,lineStart:0,lineEnd:-1},{srcId:i,lineStart:n,lineEnd:o}=Object.assign({},t,e);return this.notify(`${this.prefix}clear_highlight`,[i,n,o])}highlightRanges(e,t,i){this.client.call("coc#highlight#ranges",[this.id,e,t,i],!0)}clearNamespace(e,t=0,i=-1){this.client.call("coc#highlight#clear_highlight",[this.id,e,t,i])}listen(e,t,i){this.client.attachBufferEvent(this,e,t),i&&i.push({dispose:()=>{this.client.detachBufferEvent(this,e,t)}})}};Ah.Buffer=FL});var Wc=g(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});Oh.Window=void 0;var soe=jc(),Ew=require("timers"),AL=class extends soe.BaseApi{constructor(){super(...arguments);this.prefix="nvim_win_"}get id(){return this.data}get buffer(){return this.request(`${this.prefix}get_buf`,[])}get tabpage(){return this.request(`${this.prefix}get_tabpage`,[])}get cursor(){return this.request(`${this.prefix}get_cursor`,[])}setCursor(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_cursor`,[e])}get height(){return this.request(`${this.prefix}get_height`,[])}setHeight(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_height`,[e])}get width(){return this.request(`${this.prefix}get_width`,[])}setWidth(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_height`,[e])}get position(){return this.request(`${this.prefix}get_position`,[])}get row(){return this.request(`${this.prefix}get_position`,[]).then(e=>e[0])}get col(){return this.request(`${this.prefix}get_position`,[]).then(e=>e[1])}get valid(){return this.request(`${this.prefix}is_valid`,[])}get number(){return this.request(`${this.prefix}get_number`,[])}setConfig(e,t){return this[t?"notify":"request"](`${this.prefix}set_config`,[e])}getConfig(){return this.request(`${this.prefix}get_config`,[])}close(e,t){if(t){this.notify(`${this.prefix}close`,[e]);let i=0,n=setInterval(()=>{if(i==5)return Ew.clearInterval(n);this.request(`${this.prefix}is_valid`,[]).then(o=>{o?this.notify(`${this.prefix}close`,[e]):Ew.clearInterval(n)},()=>{Ew.clearInterval(n)}),i++},50);return null}return this.request(`${this.prefix}close`,[e])}highlightRanges(e,t,i=10,n){if(n){this.client.call("coc#highlight#match_ranges",[this.id,0,t,e,i],!0);return}return this.client.call("coc#highlight#match_ranges",[this.id,0,t,e,i])}clearMatchGroup(e){this.client.call("coc#highlight#clear_match_group",[this.id,e],!0)}clearMatches(e){this.client.call("coc#highlight#clear_matches",[this.id,e],!0)}};Oh.Window=AL});var Hc=g(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.Tabpage=void 0;var aoe=jc(),OL=class extends aoe.BaseApi{constructor(){super(...arguments);this.prefix="nvim_tabpage_"}get windows(){return this.request(`${this.prefix}list_wins`,[])}get window(){return this.request(`${this.prefix}get_win`,[])}get valid(){return this.request(`${this.prefix}is_valid`,[])}get number(){return this.request(`${this.prefix}get_number`,[])}getOption(){throw new Error("Tabpage does not have `getOption`")}setOption(){throw new Error("Tabpage does not have `setOption`")}};Lh.Tabpage=OL});var LL=g(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.Metadata=Bs.ExtType=void 0;var loe=Uc(),uoe=Wc(),coe=Hc(),foe;(function(r){r[r.Buffer=0]="Buffer",r[r.Window=1]="Window",r[r.Tabpage=2]="Tabpage"})(foe=Bs.ExtType||(Bs.ExtType={}));Bs.Metadata=[{constructor:loe.Buffer,name:"Buffer",prefix:"nvim_buf_"},{constructor:uoe.Window,name:"Window",prefix:"nvim_win_"},{constructor:coe.Tabpage,name:"Tabpage",prefix:"nvim_tabpage_"}]});var zc=g(ll=>{"use strict";var Cw=ll&&ll.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ll,"__esModule",{value:!0});ll.createLogger=void 0;var _w=Cw(require("fs")),poe=Cw(require("os")),Pw=Cw(require("path"));function doe(){let r=process.env.NODE_CLIENT_LOG_FILE;if(r)return r;let e=process.env.XDG_RUNTIME_DIR;return e?Pw.default.join(e,"node-client.log"):Pw.default.join(poe.default.tmpdir(),`node-client-${process.pid}.log`)}var Tw=doe(),ML=process.env.NODE_CLIENT_LOG_LEVEL||"info",Rw=process.getuid&&process.getuid()==0;if(!Rw)try{_w.default.mkdirSync(Pw.default.dirname(Tw),{recursive:!0}),_w.default.writeFileSync(Tw,"",{encoding:"utf8",mode:438})}catch(r){Rw=!0}function NL(r){return r==null?r:Array.isArray(r)?r.map(e=>NL(e)):typeof r=="object"&&typeof r.prefix=="string"&&typeof r.data=="number"?"["+r.prefix+r.data+"]":r}function hoe(r){return r==null?String(r):typeof r=="object"?JSON.stringify(r,null,2):String(r)}var qL=class{constructor(e){this.name=e}get stream(){return Rw?null:this._stream?this._stream:(this._stream=_w.default.createWriteStream(Tw,{encoding:"utf8"}),this._stream)}getText(e,t,i){let n="";if(i.length){let o=NL(i);n=" "+o.map(s=>hoe(s))}return`${new Date().toLocaleTimeString()} ${e.toUpperCase()} [${this.name}] - ${t}${n} +`}debug(e,...t){ML!="debug"||this.stream==null||this.stream.write(this.getText("debug",e,t))}info(e,...t){this.stream!=null&&this.stream.write(this.getText("info",e,t))}error(e,...t){this.stream!=null&&this.stream.write(this.getText("error",e,t))}trace(e,...t){ML!="trace"||this.stream==null||this.stream.write(this.getText("trace",e,t))}};function moe(r){return new qL(r)}ll.createLogger=moe});var Iw=g(kw=>{"use strict";Object.defineProperty(kw,"__esModule",{value:!0});var goe=require("events"),voe=zc(),$L=process.env.NODE_CLIENT_LOG_LEVEL=="debug",Gc=voe.createLogger("transport"),BL=class extends goe.EventEmitter{constructor(e){super();this.logger=e,this.pauseLevel=0,this.paused=new Map}debug(e,...t){!$L||Gc.debug(e,...t)}info(e,...t){Gc.info(e,...t)}debugMessage(e){if(!$L)return;let t=e[0];t==0?Gc.debug("receive request:",e.slice(1)):t==1||(t==2?Gc.debug("receive notification:",e.slice(1)):Gc.debug("unknown message:",e))}pauseNotification(){this.pauseLevel=this.pauseLevel+1,this.paused.set(this.pauseLevel,[])}cancelNotification(){let{pauseLevel:e}=this;e>0&&(this.paused.delete(e),this.pauseLevel=e-1)}resumeNotification(e=!1){let{pauseLevel:t}=this;if(t==0)return e?null:Promise.resolve([null,null]);let i=Error().stack;this.pauseLevel=t-1;let n=this.paused.get(t);return this.paused.delete(t),n&&n.length?new Promise((o,s)=>{if(!e)return this.request("nvim_call_atomic",[n],(a,l)=>{if(a){let u=new Error(`call_atomic error: ${a[1]}`);return u.stack=i,s(u)}if(Array.isArray(l)&&l[1]!=null){let[u,c,f]=l[1],[p,d]=n[u];this.logger.error(`request error ${c} on "${p}"`,d,f,i)}o(l)});this.notify("nvim_call_atomic",[n]),o()}):e?null:Promise.resolve([[],void 0])}};kw.default=BL});var WL=g(vi=>{"use strict";var yoe=vi&&vi.__createBinding||(Object.create?function(r,e,t,i){i===void 0&&(i=t),Object.defineProperty(r,i,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}),boe=vi&&vi.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),woe=vi&&vi.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&yoe(e,r,t);return boe(e,r),e},jL=vi&&vi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(vi,"__esModule",{value:!0});vi.NvimTransport=void 0;var $n=woe(TL()),xoe=jL(kL()),Doe=LL(),Soe=jL(Iw()),UL=class extends Soe.default{constructor(e){super(e);this.pending=new Map,this.nextRequestId=1,this.attached=!1;let t=this.setupCodec();this.encodeStream=$n.createEncodeStream({codec:t}),this.decodeStream=$n.createDecodeStream({codec:t}),this.decodeStream.on("data",i=>{this.parseMessage(i)}),this.decodeStream.on("end",()=>{this.detach(),this.emit("detach")})}parseMessage(e){let t=e[0];if(this.debugMessage(e),t===0)this.emit("request",e[2].toString(),e[3],this.createResponse(e[1]));else if(t===1){let i=e[1],n=this.pending.get(i);if(n){this.pending.delete(i);let o=e[2];o&&o.length!=2&&(o=[0,o instanceof Error?o.message:o]),n(o,e[3])}}else t===2?this.emit("notification",e[1].toString(),e[2]):console.error(`Invalid message type ${t}`)}setupCodec(){let e=$n.createCodec();return Doe.Metadata.forEach(({constructor:t},i)=>{e.addExtPacker(i,t,n=>$n.encode(n.data)),e.addExtUnpacker(i,n=>new t({transport:this,client:this.client,data:$n.decode(n)}))}),this.codec=e,this.codec}attach(e,t,i){this.encodeStream=this.encodeStream.pipe(e);let n=new xoe.default;t.pipe(n).pipe(this.decodeStream),this.writer=e,this.reader=t,this.client=i,this.attached=!0}detach(){!this.attached||(this.attached=!1,this.encodeStream.unpipe(this.writer),this.reader.unpipe(this.decodeStream))}request(e,t,i){if(!this.attached)return;let n=this.nextRequestId;this.nextRequestId=this.nextRequestId+1;let o=Date.now();this.debug("request to nvim:",n,e,t),this.encodeStream.write($n.encode([0,n,e,t],{codec:this.codec}));let s=Error().stack,a=setTimeout(()=>{this.debug(`request to vim blocked more than 1s: ${e}`,t,s)},1e3);this.pending.set(n,(l,u)=>{clearTimeout(a),this.debug("response of nvim:",n,`${Date.now()-o}ms`,u,l),i(l,u)})}notify(e,t){if(!!this.attached){if(this.pauseLevel!=0){let i=this.paused.get(this.pauseLevel);if(i){i.push([e,t]);return}}this.debug("nvim notification:",e,t),this.encodeStream.write($n.encode([2,e,t],{codec:this.codec}))}}send(e){this.encodeStream.write($n.encode(e,{codec:this.codec}))}createResponse(e){let{encodeStream:t}=this,i=Date.now(),n=!1,o=setTimeout(()=>{this.debug("request to client cost more than 1s",e)},1e3);return{send:(s,a)=>{clearTimeout(o),!(n||!this.attached)&&(this.debug("response of client:",e,`${Date.now()-i}ms`,s,a==!0),n=!0,t.write($n.encode([1,e,a?s:null,a?null:s])))}}}};vi.NvimTransport=UL});var GL=g(Vc=>{"use strict";var HL=Vc&&Vc.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vc,"__esModule",{value:!0});var Eoe=HL(require("events")),Coe=HL(require("readline")),_oe=zc(),ul=_oe.createLogger("connection"),b_e=process.env.NODE_CLIENT_LOG_LEVEL=="debug",zL=class extends Eoe.default{constructor(e,t){super();this.readable=e,this.writeable=t;let i=Coe.default.createInterface(this.readable);i.on("line",n=>{this.parseData(n)}),i.on("close",()=>{ul.error("connection closed"),process.exit(0)})}parseData(e){if(e.length==0)return;let t;try{t=JSON.parse(e)}catch(o){console.error(`Invalid data from vim: ${e}`);return}let[i,n]=t;i>0?(ul.debug("received request:",i,n),this.emit("request",i,n)):i==0?(ul.debug("received notification:",n),this.emit("notification",n)):(ul.debug("received response:",i,n),this.emit("response",i,n))}response(e,t){this.send([e,t||null])}notify(e,t){this.send([0,[e,t||null]])}send(e){ul.debug("send to vim:",e);try{this.writeable.write(JSON.stringify(e)+` +`)}catch(t){ul.error("Send error:",e)}}redraw(e=!1){this.send(["redraw",e?"force":""])}commmand(e){this.send(["ex",e])}expr(e){this.send(["expr",e])}call(e,t,i){if(!i){this.send(["call",e,t]);return}this.send(["call",e,t,i])}dispose(){this.removeAllListeners()}};Vc.default=zL});var KL=g(Fw=>{"use strict";Object.defineProperty(Fw,"__esModule",{value:!0});var Poe=zc(),Toe=Poe.createLogger("request"),Roe=process.env.NODE_CLIENT_LOG_LEVEL=="debug",koe=process.env.COC_NVIM=="1"?"coc#api#call":"nvim#api#call",VL=class{constructor(e,t,i){this.connection=e,this.cb=t,this.id=i}request(e,t=[]){this.method=e,this.args=t,this.connection.call(koe,[e.slice(5),t],this.id)}callback(e,t,i){let{method:n,cb:o}=this;if(Roe&&t&&Toe.debug(`request ${this.method} error:`,t,this.args),t)return o([0,t.toString()]);switch(n){case"nvim_list_wins":case"nvim_tabpage_list_wins":return o(null,i.map(s=>e.createWindow(s)));case"nvim_tabpage_get_win":case"nvim_get_current_win":case"nvim_open_win":return o(null,e.createWindow(i));case"nvim_list_bufs":return o(null,i.map(s=>e.createBuffer(s)));case"nvim_win_get_buf":case"nvim_create_buf":case"nvim_get_current_buf":return o(null,e.createBuffer(i));case"nvim_list_tabpages":return o(null,i.map(s=>e.createTabpage(s)));case"nvim_get_current_tabpage":return o(null,e.createTabpage(i));default:return o(null,i)}}};Fw.default=VL});var YL=g(cl=>{"use strict";var Aw=cl&&cl.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cl,"__esModule",{value:!0});cl.VimTransport=void 0;var Ioe=Aw(Iw()),Foe=Aw(GL()),Aoe=Aw(KL()),JL=class extends Ioe.default{constructor(e){super(e);this.pending=new Map,this.nextRequestId=-1,this.attached=!1,this.notifyMethod=process.env.COC_NVIM=="1"?"coc#api#notify":"nvim#api#notify"}attach(e,t,i){let n=this.connection=new Foe.default(t,e);this.attached=!0,this.client=i,n.on("request",(o,s)=>{let[a,l]=s;this.emit("request",a,l,this.createResponse(o))}),n.on("notification",o=>{let[s,a]=o;this.emit("notification",s.toString(),a)}),n.on("response",(o,s)=>{let a=this.pending.get(o);if(a){this.pending.delete(o);let l=null,u=null;Array.isArray(s)?(l=s[0],u=s[1]):l=s,a.callback(this.client,l,u)}})}send(e){this.connection.send(e)}detach(){!this.attached||(this.attached=!1,this.connection.dispose())}request(e,t,i){if(!this.attached)return i([0,"transport disconnected"]);let n=this.nextRequestId;this.nextRequestId=this.nextRequestId-1;let o=Date.now();this.debug("request to vim:",n,e,t);let s=setTimeout(()=>{this.debug("request to vim cost more than 1s",e,t)},1e3),a=new Aoe.default(this.connection,(l,u)=>{clearTimeout(s),this.debug("response from vim cost:",n,`${Date.now()-o}ms`),i(l,u)},n);this.pending.set(n,a),a.request(e,t)}notify(e,t){if(!!this.attached){if(this.pauseLevel!=0){let i=this.paused.get(this.pauseLevel);if(i){i.push([e,t]);return}}this.connection.call(this.notifyMethod,[e.slice(5),t])}}createResponse(e){let t=!1,{connection:i}=this,n=Date.now(),o=setTimeout(()=>{this.debug("request to client cost more than 1s",e)},1e3);return{send:(s,a)=>{if(clearTimeout(o),t||!this.attached)return;t=!0;let l=null;a&&(l=typeof s=="string"?s:s.toString()),this.debug("response of client cost:",e,`${Date.now()-n}ms`),i.response(e,[l,a?null:s])}}}};cl.VimTransport=JL});var ZL=g(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});Mh.Neovim=void 0;var Ooe=jc(),Loe=Uc(),Moe=Hc(),Noe=Wc(),qoe=process.env.VIM_NODE_RPC=="1",XL=class extends Ooe.BaseApi{constructor(){super(...arguments);this.prefix="nvim_",this.Buffer=Loe.Buffer,this.Window=Noe.Window,this.Tabpage=Moe.Tabpage}getArgs(e){return e?Array.isArray(e)?e:[e]:[]}get apiInfo(){return this.request(`${this.prefix}get_api_info`)}get buffers(){return this.request(`${this.prefix}list_bufs`)}get buffer(){return this.request(`${this.prefix}get_current_buf`)}async setBuffer(e){await this.request(`${this.prefix}set_current_buf`,[e])}get chans(){return this.request(`${this.prefix}list_chans`)}getChanInfo(e){return this.request(`${this.prefix}get_chan_info`,[e])}createNamespace(e=""){return this.request(`${this.prefix}create_namespace`,[e])}get namespaces(){return this.request(`${this.prefix}get_namespaces`,[])}get commands(){return this.getCommands()}getCommands(e={}){return this.request(`${this.prefix}get_commands`,[e])}get tabpages(){return this.request(`${this.prefix}list_tabpages`)}get tabpage(){return this.request(`${this.prefix}get_current_tabpage`)}async setTabpage(e){await this.request(`${this.prefix}set_current_tabpage`,[e])}get windows(){return this.getWindows()}get window(){return this.request(`${this.prefix}get_current_win`)}getWindows(){return this.request(`${this.prefix}list_wins`)}async setWindow(e){await this.request(`${this.prefix}set_current_win`,[e])}get runtimePaths(){return this.request(`${this.prefix}list_runtime_paths`)}setDirectory(e){return this.request(`${this.prefix}set_current_dir`,[e])}get line(){return this.getLine()}createNewBuffer(e=!1,t=!1){return this.request(`${this.prefix}create_buf`,[e,t])}openFloatWindow(e,t,i){return this.request(`${this.prefix}open_win`,[e,t,i])}getLine(){return this.request(`${this.prefix}get_current_line`)}setLine(e){return this.request(`${this.prefix}set_current_line`,[e])}getKeymap(e){return this.request(`${this.prefix}get_keymap`,[e])}get mode(){return this.request(`${this.prefix}get_mode`)}get colorMap(){return this.request(`${this.prefix}get_color_map`)}getColorByName(e){return this.request(`${this.prefix}get_color_by_name`,[e])}getHighlight(e,t=!0){let i=typeof e=="string"?"by_name":"by_id";return this.request(`${this.prefix}get_hl_${i}`,[e,t])}getHighlightByName(e,t=!0){return this.request(`${this.prefix}get_hl_by_name`,[e,t])}getHighlightById(e,t=!0){return this.request(`${this.prefix}get_hl_by_id`,[e,t])}deleteCurrentLine(){return this.request(`${this.prefix}del_current_line`)}eval(e){return this.request(`${this.prefix}eval`,[e])}lua(e,t=[]){let i=this.getArgs(t);return this.request(`${this.prefix}execute_lua`,[e,i])}executeLua(e,t=[]){return this.lua(e,t)}callDictFunction(e,t,i=[]){let n=this.getArgs(i);return this.request(`${this.prefix}call_dict_function`,[e,t,n])}call(e,t=[],i){let n=this.getArgs(t);return i?(this.notify(`${this.prefix}call_function`,[e,n]),null):this.request(`${this.prefix}call_function`,[e,n])}callTimer(e,t=[],i){let n=this.getArgs(t);return i?(this.notify(`${this.prefix}call_function`,["coc#util#timer",[e,n]]),null):qoe?(this.notify(`${this.prefix}call_function`,["coc#util#timer",[e,n]]),new Promise(o=>{setTimeout(()=>{o(null)},20)})):this.request(`${this.prefix}call_function`,["coc#util#timer",[e,n]])}callAsync(e,t=[]){let i=this.getArgs(t);return this.client.sendAsyncRequest(e,i)}callFunction(e,t=[]){return this.call(e,t)}callAtomic(e){return this.request(`${this.prefix}call_atomic`,[e])}command(e,t){return t?(this.notify(`${this.prefix}command`,[e]),null):this.request(`${this.prefix}command`,[e])}commandOutput(e){return this.request(`${this.prefix}command_output`,[e])}getVvar(e){return this.request(`${this.prefix}get_vvar`,[e])}feedKeys(e,t,i){return this.request(`${this.prefix}feedkeys`,[e,t,i])}input(e){return this.request(`${this.prefix}input`,[e])}parseExpression(e,t,i){return this.request(`${this.prefix}parse_expression`,[e,t,i])}getProc(e){return this.request(`${this.prefix}get_proc`,[e])}getProcChildren(e){return this.request(`${this.prefix}get_proc_children`,[e])}replaceTermcodes(e,t,i,n){return this.request(`${this.prefix}replace_termcodes`,[e,t,i,n])}strWidth(e){return this.request(`${this.prefix}strwidth`,[e])}outWrite(e){this.notify(`${this.prefix}out_write`,[e])}outWriteLine(e){this.outWrite(`${e} +`)}errWrite(e){this.notify(`${this.prefix}err_write`,[e])}errWriteLine(e){this.notify(`${this.prefix}err_writeln`,[e])}get uis(){return this.request(`${this.prefix}list_uis`)}uiAttach(e,t,i){return this.request(`${this.prefix}ui_attach`,[e,t,i])}uiDetach(){return this.request(`${this.prefix}ui_detach`,[])}uiTryResize(e,t){return this.request(`${this.prefix}ui_try_resize`,[e,t])}uiSetOption(e,t){return this.request(`${this.prefix}ui_set_option`,[e,t])}subscribe(e){return this.request(`${this.prefix}subscribe`,[e])}unsubscribe(e){return this.request(`${this.prefix}unsubscribe`,[e])}setClientInfo(e,t,i,n,o){this.notify(`${this.prefix}set_client_info`,[e,t,i,n,o])}async quit(){this.command("qa!",!0),this.transport&&this.transport.detach()}};Mh.Neovim=XL});var Nh=g(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.NeovimClient=fl.AsyncResponse=void 0;var $oe=WL(),Boe=YL(),joe=ZL(),Uoe=Uc(),Woe=Wc(),Hoe=Hc(),zoe=zc(),QL=zoe.createLogger("client"),Goe=process.env.VIM_NODE_RPC=="1",Ow=class{constructor(e,t){this.requestId=e,this.cb=t,this.finished=!1}finish(e,t){if(!this.finished){if(this.finished=!0,e){this.cb(new Error(e));return}this.cb(null,t)}}};fl.AsyncResponse=Ow;var eM=class extends joe.Neovim{constructor(e){super({});this.logger=e,this.requestId=1,this.responses=new Map,this.attachedBuffers=new Map,Object.defineProperty(this,"client",{value:this});let t=Goe?new Boe.VimTransport(e):new $oe.NvimTransport(e);this.setTransport(t),this.transportAttached=!1,this.handleRequest=this.handleRequest.bind(this),this.handleNotification=this.handleNotification.bind(this)}logError(e,...t){!this.logger||this.logger.error(e,...t)}createBuffer(e){return new Uoe.Buffer({transport:this.transport,data:e,client:this})}createWindow(e){return new Woe.Window({transport:this.transport,data:e,client:this})}createTabpage(e){return new Hoe.Tabpage({transport:this.transport,data:e,client:this})}send(e){this.transport.send(e)}attach({reader:e,writer:t},i=!0){this.transport.attach(t,e,this),this.transportAttached=!0,this.setupTransport(i)}detach(){this.transport.detach(),this.transportAttached=!1}get isApiReady(){return this.transportAttached&&typeof this._channelId!="undefined"}get channelId(){return this._isReady.then(()=>this._channelId)}isAttached(e){return this.attachedBuffers.has(e)}handleRequest(e,t,i){this.emit("request",e,t,i)}sendAsyncRequest(e,t){let i=this.requestId;return this.requestId=i+1,this.notify("nvim_call_function",["coc#rpc#async_request",[i,e,t||[]]]),new Promise((n,o)=>{let s=new Ow(i,(a,l)=>{if(a)return o(a);n(l)});this.responses.set(i,s)})}emitNotification(e,t){if(e.endsWith("_event")){if(e.startsWith("nvim_buf_")){let i=e.replace(/nvim_buf_(.*)_event/,"$1"),{id:n}=t[0];if(!this.attachedBuffers.has(n))return;(this.attachedBuffers.get(n).get(i)||[]).forEach(a=>a(...t)),i==="detach"&&this.attachedBuffers.delete(n);return}if(e.startsWith("nvim_async_request")){let[i,n,o]=t;this.handleRequest(n,o,{send:(s,a)=>{this.notify("nvim_call_function",["coc#rpc#async_response",[i,s,a]])}})}if(e.startsWith("nvim_async_response")){let[i,n,o]=t,s=this.responses.get(i);if(!s){console.error(`Response not found for request ${i}`);return}this.responses.delete(i),s.finish(n,o);return}}else this.emit("notification",e,t)}handleNotification(e,t){this.emitNotification(e,t)}setupTransport(e=!0){if(!this.transportAttached)throw new Error("Not attached to input/output");this.transport.on("request",this.handleRequest),this.transport.on("notification",this.handleNotification),this.transport.on("detach",()=>{this.emit("disconnect"),this.transport.removeAllListeners("request"),this.transport.removeAllListeners("notification"),this.transport.removeAllListeners("detach")}),e?this._isReady=this.generateApi():(this._channelId=0,this._isReady=Promise.resolve(!0))}requestApi(){return new Promise((e,t)=>{this.transport.request("nvim_get_api_info",[],(i,n)=>{i?t(new Error(Array.isArray(i)?i[1]:i.message||i.toString())):e(n)})})}async generateApi(){let e;try{e=await this.requestApi()}catch(t){console.error("Could not get vim api results"),QL.error(t)}if(e)try{let[t,i]=e;return this.functions=i.functions.map(n=>n.name),this._channelId=t,!0}catch(t){return QL.error(t.stack),null}return null}attachBufferEvent(e,t,i){let n=this.attachedBuffers.get(e.id)||new Map,o=n.get(t)||[];o.includes(i)||(o.push(i),n.set(t,o),this.attachedBuffers.set(e.id,n))}detachBufferEvent(e,t,i){let n=this.attachedBuffers.get(e.id);if(!n||!n.has(t))return;let o=n.get(t).filter(s=>s!==i);n.set(t,o)}pauseNotification(){this.transport.pauseNotification();let e=Error().stack;process.nextTick(()=>{this.transport.pauseLevel>0&&this.logError("resumeNotification not called within same tick:",e)})}resumeNotification(e,t){return e?Promise.resolve(this.transport.cancelNotification()):t?Promise.resolve(this.transport.resumeNotification(!0)):Promise.resolve(this.transport.resumeNotification())}hasFunction(e){return this.functions?this.functions.indexOf(e)!==-1:!0}};fl.NeovimClient=eM});var tM=g(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});qh.attach=void 0;var Voe=require("net"),Koe=Nh();function Joe({reader:r,writer:e,proc:t,socket:i},n=null,o=!0){let s,a,l;if(i){let u=Voe.createConnection(i);s=u,a=u,u.once("close",()=>{l.detach()})}else r&&e?(s=e,a=r):t&&(s=t.stdin,a=t.stdout,t.once("disconnect",()=>{l.detach()}));if(s.on("error",u=>{u.code=="EPIPE"&&l.detach()}),s&&a)return l=new Koe.NeovimClient(n),l.attach({writer:s,reader:a},o),l;throw new Error("Invalid arguments, could not attach")}qh.attach=Joe});var rM=g(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.Tabpage=yi.Window=yi.Buffer=yi.NeovimClient=yi.Neovim=void 0;var Yoe=Nh();Object.defineProperty(yi,"Neovim",{enumerable:!0,get:function(){return Yoe.NeovimClient}});var Xoe=Nh();Object.defineProperty(yi,"NeovimClient",{enumerable:!0,get:function(){return Xoe.NeovimClient}});var Zoe=Uc();Object.defineProperty(yi,"Buffer",{enumerable:!0,get:function(){return Zoe.Buffer}});var Qoe=Wc();Object.defineProperty(yi,"Window",{enumerable:!0,get:function(){return Qoe.Window}});var ese=Hc();Object.defineProperty(yi,"Tabpage",{enumerable:!0,get:function(){return ese.Tabpage}})});var Lw=g(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.Window=Tr.Tabpage=Tr.Buffer=Tr.NeovimClient=Tr.Neovim=Tr.attach=void 0;var tse=tM();Object.defineProperty(Tr,"attach",{enumerable:!0,get:function(){return tse.attach}});var Kc=rM();Object.defineProperty(Tr,"Neovim",{enumerable:!0,get:function(){return Kc.Neovim}});Object.defineProperty(Tr,"NeovimClient",{enumerable:!0,get:function(){return Kc.NeovimClient}});Object.defineProperty(Tr,"Buffer",{enumerable:!0,get:function(){return Kc.Buffer}});Object.defineProperty(Tr,"Tabpage",{enumerable:!0,get:function(){return Kc.Tabpage}});Object.defineProperty(Tr,"Window",{enumerable:!0,get:function(){return Kc.Window}})});var pl=g(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});function rse(r){return r===!0||r===!1}Bn.boolean=rse;function iM(r){return typeof r=="string"||r instanceof String}Bn.string=iM;function ise(r){return typeof r=="number"||r instanceof Number}Bn.number=ise;function nse(r){return r instanceof Error}Bn.error=nse;function ose(r){return typeof r=="function"}Bn.func=ose;function nM(r){return Array.isArray(r)}Bn.array=nM;function sse(r){return nM(r)&&r.every(e=>iM(e))}Bn.stringArray=sse});var TM=g(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});var js=pl(),oM;(function(r){r.ParseError=-32700,r.InvalidRequest=-32600,r.MethodNotFound=-32601,r.InvalidParams=-32602,r.InternalError=-32603,r.serverErrorStart=-32099,r.serverErrorEnd=-32e3,r.ServerNotInitialized=-32002,r.UnknownErrorCode=-32001,r.RequestCancelled=-32800,r.ContentModified=-32801,r.MessageWriteError=1,r.MessageReadError=2})(oM=Le.ErrorCodes||(Le.ErrorCodes={}));var $h=class extends Error{constructor(e,t,i){super(t);this.code=js.number(e)?e:oM.UnknownErrorCode,this.data=i,Object.setPrototypeOf(this,$h.prototype)}toJson(){return{code:this.code,message:this.message,data:this.data}}};Le.ResponseError=$h;var ot=class{constructor(e,t){this._method=e,this._numberOfParams=t}get method(){return this._method}get numberOfParams(){return this._numberOfParams}};Le.AbstractMessageType=ot;var sM=class extends ot{constructor(e){super(e,0)}};Le.RequestType0=sM;var aM=class extends ot{constructor(e){super(e,1)}};Le.RequestType=aM;var lM=class extends ot{constructor(e){super(e,1)}};Le.RequestType1=lM;var uM=class extends ot{constructor(e){super(e,2)}};Le.RequestType2=uM;var cM=class extends ot{constructor(e){super(e,3)}};Le.RequestType3=cM;var fM=class extends ot{constructor(e){super(e,4)}};Le.RequestType4=fM;var pM=class extends ot{constructor(e){super(e,5)}};Le.RequestType5=pM;var dM=class extends ot{constructor(e){super(e,6)}};Le.RequestType6=dM;var hM=class extends ot{constructor(e){super(e,7)}};Le.RequestType7=hM;var mM=class extends ot{constructor(e){super(e,8)}};Le.RequestType8=mM;var gM=class extends ot{constructor(e){super(e,9)}};Le.RequestType9=gM;var vM=class extends ot{constructor(e){super(e,1);this._=void 0}};Le.NotificationType=vM;var yM=class extends ot{constructor(e){super(e,0)}};Le.NotificationType0=yM;var bM=class extends ot{constructor(e){super(e,1)}};Le.NotificationType1=bM;var wM=class extends ot{constructor(e){super(e,2)}};Le.NotificationType2=wM;var xM=class extends ot{constructor(e){super(e,3)}};Le.NotificationType3=xM;var DM=class extends ot{constructor(e){super(e,4)}};Le.NotificationType4=DM;var SM=class extends ot{constructor(e){super(e,5)}};Le.NotificationType5=SM;var EM=class extends ot{constructor(e){super(e,6)}};Le.NotificationType6=EM;var CM=class extends ot{constructor(e){super(e,7)}};Le.NotificationType7=CM;var _M=class extends ot{constructor(e){super(e,8)}};Le.NotificationType8=_M;var PM=class extends ot{constructor(e){super(e,9)}};Le.NotificationType9=PM;function ase(r){let e=r;return e&&js.string(e.method)&&(js.string(e.id)||js.number(e.id))}Le.isRequestMessage=ase;function lse(r){let e=r;return e&&js.string(e.method)&&r.id===void 0}Le.isNotificationMessage=lse;function use(r){let e=r;return e&&(e.result!==void 0||!!e.error)&&(js.string(e.id)||js.number(e.id)||e.id===null)}Le.isResponseMessage=use});var Yc=g(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var cse;(function(r){function e(t){return{dispose:t}}r.create=e})(cse=Us.Disposable||(Us.Disposable={}));var fse;(function(r){let e={dispose(){}};r.None=function(){return e}})(fse=Us.Event||(Us.Event={}));var RM=class{add(e,t=null,i){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(i)&&i.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!!this._callbacks){for(var i=!1,n=0,o=this._callbacks.length;n{this._callbacks||(this._callbacks=new RM),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);let n;return n={dispose:()=>{this._callbacks.remove(e,t),n.dispose=Jc._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this)}},Array.isArray(i)&&i.push(n),n}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};Us.Emitter=Jc;Jc._noop=function(){}});var jh=g(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Mw=Yc(),dl=pl(),Nw=8192,kM=Buffer.from("\r","ascii")[0],IM=Buffer.from(` +`,"ascii")[0],pse=`\r +`,FM=class{constructor(e="utf8"){this.encoding=e,this.index=0,this.buffer=Buffer.allocUnsafe(Nw)}append(e){var t=e;if(typeof e=="string"){var i=e,n=Buffer.byteLength(i,this.encoding);t=Buffer.allocUnsafe(n),t.write(i,0,n,this.encoding)}if(this.buffer.length-this.index>=t.length)t.copy(this.buffer,this.index,0,t.length);else{var o=(Math.ceil((this.index+t.length)/Nw)+1)*Nw;this.index===0?(this.buffer=Buffer.allocUnsafe(o),t.copy(this.buffer,0,0,t.length)):this.buffer=Buffer.concat([this.buffer.slice(0,this.index),t],o)}this.index+=t.length}tryReadHeaders(){let e,t=0;for(;t+3=this.index)return e;e=Object.create(null),this.buffer.toString("ascii",0,t).split(pse).forEach(o=>{let s=o.indexOf(":");if(s===-1)throw new Error("Message header must separate key and value using :");let a=o.substr(0,s),l=o.substr(s+1).trim();e[a]=l});let n=t+4;return this.buffer=this.buffer.slice(n),this.index=this.index-n,e}tryReadContent(e){if(this.index{this.onData(t)}),this.readable.on("error",t=>this.fireError(t)),this.readable.on("close",()=>this.fireClose())}onData(e){for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let n=this.buffer.tryReadHeaders();if(!n)return;let o=n["Content-Length"];if(!o)throw new Error("Header must provide a Content-Length property.");let s=parseInt(o);if(isNaN(s))throw new Error("Content-Length value must be a number.");this.nextMessageLength=s}var t=this.buffer.tryReadContent(this.nextMessageLength);if(t===null){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.messageToken++;var i=JSON.parse(t);this.callback(i)}}clearPartialMessageTimer(){this.partialMessageTimer&&(clearTimeout(this.partialMessageTimer),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};To.StreamMessageReader=qw;var AM=class extends Bh{constructor(e){super();this.process=e;let t=this.process;t.on("error",i=>this.fireError(i)),t.on("close",()=>this.fireClose())}listen(e){this.process.on("message",e)}};To.IPCMessageReader=AM;var OM=class extends qw{constructor(e,t="utf-8"){super(e,t)}};To.SocketMessageReader=OM});var Wh=g(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});var LM=Yc(),Xc=pl(),MM="Content-Length: ",Uh=`\r +`,hse;(function(r){function e(t){let i=t;return i&&Xc.func(i.dispose)&&Xc.func(i.onClose)&&Xc.func(i.onError)&&Xc.func(i.write)}r.is=e})(hse=Ro.MessageWriter||(Ro.MessageWriter={}));var Zc=class{constructor(){this.errorEmitter=new LM.Emitter,this.closeEmitter=new LM.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,i){this.errorEmitter.fire([this.asError(e),t,i])}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: ${Xc.string(e.message)?e.message:"unknown"}`)}};Ro.AbstractMessageWriter=Zc;var NM=class extends Zc{constructor(e,t="utf8"){super();this.writable=e,this.encoding=t,this.errorCount=0,this.writable.on("error",i=>this.fireError(i)),this.writable.on("close",()=>this.fireClose())}write(e){let t=JSON.stringify(e),i=Buffer.byteLength(t,this.encoding),n=[MM,i.toString(),Uh,Uh];try{this.writable.write(n.join(""),"ascii"),this.writable.write(t,this.encoding),this.errorCount=0}catch(o){this.errorCount++,this.fireError(o,e,this.errorCount)}}};Ro.StreamMessageWriter=NM;var qM=class extends Zc{constructor(e){super();this.process=e,this.errorCount=0,this.queue=[],this.sending=!1;let t=this.process;t.on("error",i=>this.fireError(i)),t.on("close",()=>this.fireClose)}write(e){!this.sending&&this.queue.length===0?this.doWriteMessage(e):this.queue.push(e)}doWriteMessage(e){try{this.process.send&&(this.sending=!0,this.process.send(e,void 0,void 0,t=>{this.sending=!1,t?(this.errorCount++,this.fireError(t,e,this.errorCount)):this.errorCount=0,this.queue.length>0&&this.doWriteMessage(this.queue.shift())}))}catch(t){this.errorCount++,this.fireError(t,e,this.errorCount)}}};Ro.IPCMessageWriter=qM;var $M=class extends Zc{constructor(e,t="utf8"){super();this.socket=e,this.queue=[],this.sending=!1,this.encoding=t,this.errorCount=0,this.socket.on("error",i=>this.fireError(i)),this.socket.on("close",()=>this.fireClose())}dispose(){super.dispose(),this.socket.destroy()}write(e){!this.sending&&this.queue.length===0?this.doWriteMessage(e):this.queue.push(e)}doWriteMessage(e){let t=JSON.stringify(e),i=Buffer.byteLength(t,this.encoding),n=[MM,i.toString(),Uh,Uh];try{this.sending=!0,this.socket.write(n.join(""),"ascii",o=>{o&&this.handleError(o,e);try{this.socket.write(t,this.encoding,s=>{this.sending=!1,s?this.handleError(s,e):this.errorCount=0,this.queue.length>0&&this.doWriteMessage(this.queue.shift())})}catch(s){this.handleError(s,e)}})}catch(o){this.handleError(o,e)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}};Ro.SocketMessageWriter=$M});var jM=g(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var $w=Yc(),mse=pl(),Bw;(function(r){r.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:$w.Event.None}),r.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:$w.Event.None});function e(t){let i=t;return i&&(i===r.None||i===r.Cancelled||mse.boolean(i.isCancellationRequested)&&!!i.onCancellationRequested)}r.is=e})(Bw=Qc.CancellationToken||(Qc.CancellationToken={}));var gse=Object.freeze(function(r,e){let t=setTimeout(r.bind(e),0);return{dispose(){clearTimeout(t)}}}),jw=class{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?gse:(this._emitter||(this._emitter=new $w.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},BM=class{get token(){return this._token||(this._token=new jw),this._token}cancel(){this._token?this._token.cancel():this._token=Bw.Cancelled}dispose(){this._token?this._token instanceof jw&&this._token.dispose():this._token=Bw.None}};Qc.CancellationTokenSource=BM});var WM=g(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var dn;(function(r){r.None=0,r.First=1,r.Last=2})(dn=ef.Touch||(ef.Touch={}));var UM=class{constructor(){this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}has(e){return this._map.has(e)}get(e){let t=this._map.get(e);if(!!t)return t.value}set(e,t,i=dn.None){let n=this._map.get(e);if(n)n.value=t,i!==dn.None&&this.touch(n,i);else{switch(n={key:e,value:t,next:void 0,previous:void 0},i){case dn.None:this.addItemLast(n);break;case dn.First:this.addItemFirst(n);break;case dn.Last:this.addItemLast(n);break;default:this.addItemLast(n);break}this._map.set(e,n),this._size++}}delete(e){let t=this._map.get(e);return t?(this._map.delete(e),this.removeItem(t),this._size--,!0):!1}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let i=this._head;for(;i;)t?e.bind(t)(i.value,i.key,this):e(i.value,i.key,this),i=i.next}forEachReverse(e,t){let i=this._tail;for(;i;)t?e.bind(t)(i.value,i.key,this):e(i.value,i.key,this),i=i.previous}values(){let e=[],t=this._head;for(;t;)e.push(t.value),t=t.next;return e}keys(){let e=[],t=this._head;for(;t;)e.push(t.key),t=t.next;return e}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw new Error("Invalid list");this._head=e}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw new Error("Invalid list");this._tail=e}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head)this._head=e.next;else if(e===this._tail)this._tail=e.previous;else{let t=e.next,i=e.previous;if(!t||!i)throw new Error("Invalid list");t.previous=i,i.next=t}}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(t!==dn.First&&t!==dn.Last)){if(t===dn.First){if(e===this._head)return;let i=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(i.previous=n,n.next=i),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e}else if(t===dn.Last){if(e===this._tail)return;let i=e.next,n=e.previous;e===this._head?(i.previous=void 0,this._head=i):(i.previous=n,n.next=i),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e}}}};ef.LinkedMap=UM});var VM=g(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var vse=require("path"),yse=require("os"),bse=require("crypto"),HM=require("net"),zM=jh(),GM=Wh();function wse(){let r=bse.randomBytes(21).toString("hex");return process.platform==="win32"?`\\\\.\\pipe\\vscode-jsonrpc-${r}-sock`:vse.join(yse.tmpdir(),`vscode-${r}.sock`)}tf.generateRandomPipeName=wse;function xse(r,e="utf-8"){let t,i=new Promise((n,o)=>{t=n});return new Promise((n,o)=>{let s=HM.createServer(a=>{s.close(),t([new zM.SocketMessageReader(a,e),new GM.SocketMessageWriter(a,e)])});s.on("error",o),s.listen(r,()=>{s.removeListener("error",o),n({onConnected:()=>i})})})}tf.createClientPipeTransport=xse;function Dse(r,e="utf-8"){let t=HM.createConnection(r);return[new zM.SocketMessageReader(t,e),new GM.SocketMessageWriter(t,e)]}tf.createServerPipeTransport=Dse});var XM=g(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var KM=require("net"),JM=jh(),YM=Wh();function Sse(r,e="utf-8"){let t,i=new Promise((n,o)=>{t=n});return new Promise((n,o)=>{let s=KM.createServer(a=>{s.close(),t([new JM.SocketMessageReader(a,e),new YM.SocketMessageWriter(a,e)])});s.on("error",o),s.listen(r,"127.0.0.1",()=>{s.removeListener("error",o),n({onConnected:()=>i})})})}Hh.createClientSocketTransport=Sse;function Ese(r,e="utf-8"){let t=KM.createConnection(r,"127.0.0.1");return[new JM.SocketMessageReader(t,e),new YM.SocketMessageWriter(t,e)]}Hh.createServerSocketTransport=Ese});var bi=g(Q=>{"use strict";function ZM(r){for(var e in r)Q.hasOwnProperty(e)||(Q[e]=r[e])}Object.defineProperty(Q,"__esModule",{value:!0});var jt=pl(),ne=TM();Q.RequestType=ne.RequestType;Q.RequestType0=ne.RequestType0;Q.RequestType1=ne.RequestType1;Q.RequestType2=ne.RequestType2;Q.RequestType3=ne.RequestType3;Q.RequestType4=ne.RequestType4;Q.RequestType5=ne.RequestType5;Q.RequestType6=ne.RequestType6;Q.RequestType7=ne.RequestType7;Q.RequestType8=ne.RequestType8;Q.RequestType9=ne.RequestType9;Q.ResponseError=ne.ResponseError;Q.ErrorCodes=ne.ErrorCodes;Q.NotificationType=ne.NotificationType;Q.NotificationType0=ne.NotificationType0;Q.NotificationType1=ne.NotificationType1;Q.NotificationType2=ne.NotificationType2;Q.NotificationType3=ne.NotificationType3;Q.NotificationType4=ne.NotificationType4;Q.NotificationType5=ne.NotificationType5;Q.NotificationType6=ne.NotificationType6;Q.NotificationType7=ne.NotificationType7;Q.NotificationType8=ne.NotificationType8;Q.NotificationType9=ne.NotificationType9;var rf=jh();Q.MessageReader=rf.MessageReader;Q.StreamMessageReader=rf.StreamMessageReader;Q.IPCMessageReader=rf.IPCMessageReader;Q.SocketMessageReader=rf.SocketMessageReader;var nf=Wh();Q.MessageWriter=nf.MessageWriter;Q.StreamMessageWriter=nf.StreamMessageWriter;Q.IPCMessageWriter=nf.IPCMessageWriter;Q.SocketMessageWriter=nf.SocketMessageWriter;var ko=Yc();Q.Disposable=ko.Disposable;Q.Event=ko.Event;Q.Emitter=ko.Emitter;var hl=jM();Q.CancellationTokenSource=hl.CancellationTokenSource;Q.CancellationToken=hl.CancellationToken;var QM=WM();ZM(VM());ZM(XM());var of;(function(r){r.type=new ne.NotificationType("$/cancelRequest")})(of||(of={}));var zh;(function(r){r.type=new ne.NotificationType("$/progress")})(zh||(zh={}));var eN=class{constructor(){}};Q.ProgressType=eN;Q.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var yt;(function(r){r[r.Off=0]="Off",r[r.Messages=1]="Messages",r[r.Verbose=2]="Verbose"})(yt=Q.Trace||(Q.Trace={}));(function(r){function e(i){if(!jt.string(i))return r.Off;switch(i=i.toLowerCase(),i){case"off":return r.Off;case"messages":return r.Messages;case"verbose":return r.Verbose;default:return r.Off}}r.fromString=e;function t(i){switch(i){case r.Off:return"off";case r.Messages:return"messages";case r.Verbose:return"verbose";default:return"off"}}r.toString=t})(yt=Q.Trace||(Q.Trace={}));var ji;(function(r){r.Text="text",r.JSON="json"})(ji=Q.TraceFormat||(Q.TraceFormat={}));(function(r){function e(t){return t=t.toLowerCase(),t==="json"?r.JSON:r.Text}r.fromString=e})(ji=Q.TraceFormat||(Q.TraceFormat={}));var tN;(function(r){r.type=new ne.NotificationType("$/setTraceNotification")})(tN=Q.SetTraceNotification||(Q.SetTraceNotification={}));var Uw;(function(r){r.type=new ne.NotificationType("$/logTraceNotification")})(Uw=Q.LogTraceNotification||(Q.LogTraceNotification={}));var Gh;(function(r){r[r.Closed=1]="Closed",r[r.Disposed=2]="Disposed",r[r.AlreadyListening=3]="AlreadyListening"})(Gh=Q.ConnectionErrors||(Q.ConnectionErrors={}));var Ws=class extends Error{constructor(e,t){super(t);this.code=e,Object.setPrototypeOf(this,Ws.prototype)}};Q.ConnectionError=Ws;var Cse;(function(r){function e(t){let i=t;return i&&jt.func(i.cancelUndispatched)}r.is=e})(Cse=Q.ConnectionStrategy||(Q.ConnectionStrategy={}));var Ui;(function(r){r[r.New=1]="New",r[r.Listening=2]="Listening",r[r.Closed=3]="Closed",r[r.Disposed=4]="Disposed"})(Ui||(Ui={}));function _se(r,e,t,i){let n=0,o=0,s=0,a="2.0",l,u=Object.create(null),c,f=Object.create(null),p=new Map,d,h=new QM.LinkedMap,m=Object.create(null),y=Object.create(null),v=yt.Off,x=ji.Text,w,E=Ui.New,P=new ko.Emitter,k=new ko.Emitter,_=new ko.Emitter,O=new ko.Emitter,I=new ko.Emitter;function L(T){return"req-"+T.toString()}function R(T){return T===null?"res-unknown-"+(++s).toString():"res-"+T.toString()}function F(){return"not-"+(++o).toString()}function q(T,B){ne.isRequestMessage(B)?T.set(L(B.id),B):ne.isResponseMessage(B)?T.set(R(B.id),B):T.set(F(),B)}function K(T){}function ae(){return E===Ui.Listening}function Pe(){return E===Ui.Closed}function We(){return E===Ui.Disposed}function Yt(){(E===Ui.New||E===Ui.Listening)&&(E=Ui.Closed,k.fire(void 0))}function Nt(T){P.fire([T,void 0,void 0])}function dr(T){P.fire(T)}r.onClose(Yt),r.onError(Nt),e.onClose(Yt),e.onError(dr);function kn(){d||h.size===0||(d=setImmediate(()=>{d=void 0,In()}))}function In(){if(h.size===0)return;let T=h.shift();try{ne.isRequestMessage(T)?Dd(T):ne.isNotificationMessage(T)?Fa(T):ne.isResponseMessage(T)?_y(T):Aa(T)}finally{kn()}}let Cy=T=>{try{if(ne.isNotificationMessage(T)&&T.method===of.type.method){let B=L(T.params.id),V=h.get(B);if(ne.isRequestMessage(V)){let te=i&&i.cancelUndispatched?i.cancelUndispatched(V,K):K(V);if(te&&(te.error!==void 0||te.result!==void 0)){h.delete(B),te.id=V.id,fe(te,T.method,Date.now()),e.write(te);return}}}q(h,T)}finally{kn()}};function Dd(T){if(We())return;function B(tt,hr,rt){let Zt={jsonrpc:a,id:T.id};tt instanceof ne.ResponseError?Zt.error=tt.toJson():Zt.result=tt===void 0?null:tt,fe(Zt,hr,rt),e.write(Zt)}function V(tt,hr,rt){let Zt={jsonrpc:a,id:T.id,error:tt.toJson()};fe(Zt,hr,rt),e.write(Zt)}function te(tt,hr,rt){tt===void 0&&(tt=null);let Zt={jsonrpc:a,id:T.id,result:tt};fe(Zt,hr,rt),e.write(Zt)}Ee(T);let Qe=u[T.method],si,ln;Qe&&(si=Qe.type,ln=Qe.handler);let _t=Date.now();if(ln||l){let tt=new hl.CancellationTokenSource,hr=String(T.id);y[hr]=tt;try{let rt;T.params===void 0||si!==void 0&&si.numberOfParams===0?rt=ln?ln(tt.token):l(T.method,tt.token):jt.array(T.params)&&(si===void 0||si.numberOfParams>1)?rt=ln?ln(...T.params,tt.token):l(T.method,...T.params,tt.token):rt=ln?ln(T.params,tt.token):l(T.method,T.params,tt.token);let Zt=rt;rt?Zt.then?Zt.then(ms=>{delete y[hr],B(ms,T.method,_t)},ms=>{delete y[hr],ms instanceof ne.ResponseError?V(ms,T.method,_t):ms&&jt.string(ms.message)?V(new ne.ResponseError(ne.ErrorCodes.InternalError,`Request ${T.method} failed with message: ${ms.message}`),T.method,_t):V(new ne.ResponseError(ne.ErrorCodes.InternalError,`Request ${T.method} failed unexpectedly without providing any details.`),T.method,_t)}):(delete y[hr],B(rt,T.method,_t)):(delete y[hr],te(rt,T.method,_t))}catch(rt){delete y[hr],rt instanceof ne.ResponseError?B(rt,T.method,_t):rt&&jt.string(rt.message)?V(new ne.ResponseError(ne.ErrorCodes.InternalError,`Request ${T.method} failed with message: ${rt.message}`),T.method,_t):V(new ne.ResponseError(ne.ErrorCodes.InternalError,`Request ${T.method} failed unexpectedly without providing any details.`),T.method,_t)}}else V(new ne.ResponseError(ne.ErrorCodes.MethodNotFound,`Unhandled method ${T.method}`),T.method,_t)}function _y(T){if(!We())if(T.id===null)T.error?t.error(`Received response message without id: Error is: +${JSON.stringify(T.error,void 0,4)}`):t.error("Received response message without id. No further error information provided.");else{let B=String(T.id),V=m[B];if(Oi(T,V),V){delete m[B];try{if(T.error){let te=T.error;V.reject(new ne.ResponseError(te.code,te.message,te.data))}else if(T.result!==void 0)V.resolve(T.result);else throw new Error("Should never happen.")}catch(te){te.message?t.error(`Response handler '${V.method}' failed with message: ${te.message}`):t.error(`Response handler '${V.method}' failed unexpectedly.`)}}}}function Fa(T){if(We())return;let B,V;if(T.method===of.type.method)V=te=>{let Qe=te.id,si=y[String(Qe)];si&&si.cancel()};else{let te=f[T.method];te&&(V=te.handler,B=te.type)}if(V||c)try{Ct(T),T.params===void 0||B!==void 0&&B.numberOfParams===0?V?V():c(T.method):jt.array(T.params)&&(B===void 0||B.numberOfParams>1)?V?V(...T.params):c(T.method,...T.params):V?V(T.params):c(T.method,T.params)}catch(te){te.message?t.error(`Notification handler '${T.method}' failed with message: ${te.message}`):t.error(`Notification handler '${T.method}' failed unexpectedly.`)}else _.fire(T)}function Aa(T){if(!T){t.error("Received empty message.");return}t.error(`Received message which is neither a response nor a notification message: +${JSON.stringify(T,null,4)}`);let B=T;if(jt.string(B.id)||jt.number(B.id)){let V=String(B.id),te=m[V];te&&te.reject(new Error("The received response has neither a result nor an error property."))}}function Se(T){if(!(v===yt.Off||!w))if(x===ji.Text){let B;v===yt.Verbose&&T.params&&(B=`Params: ${JSON.stringify(T.params,null,4)} + +`),w.log(`Sending request '${T.method} - (${T.id})'.`,B)}else Xt("send-request",T)}function ve(T){if(!(v===yt.Off||!w))if(x===ji.Text){let B;v===yt.Verbose&&(T.params?B=`Params: ${JSON.stringify(T.params,null,4)} + +`:B=`No parameters provided. + +`),w.log(`Sending notification '${T.method}'.`,B)}else Xt("send-notification",T)}function fe(T,B,V){if(!(v===yt.Off||!w))if(x===ji.Text){let te;v===yt.Verbose&&(T.error&&T.error.data?te=`Error data: ${JSON.stringify(T.error.data,null,4)} + +`:T.result?te=`Result: ${JSON.stringify(T.result,null,4)} + +`:T.error===void 0&&(te=`No result returned. + +`)),w.log(`Sending response '${B} - (${T.id})'. Processing request took ${Date.now()-V}ms`,te)}else Xt("send-response",T)}function Ee(T){if(!(v===yt.Off||!w))if(x===ji.Text){let B;v===yt.Verbose&&T.params&&(B=`Params: ${JSON.stringify(T.params,null,4)} + +`),w.log(`Received request '${T.method} - (${T.id})'.`,B)}else Xt("receive-request",T)}function Ct(T){if(!(v===yt.Off||!w||T.method===Uw.type.method))if(x===ji.Text){let B;v===yt.Verbose&&(T.params?B=`Params: ${JSON.stringify(T.params,null,4)} + +`:B=`No parameters provided. + +`),w.log(`Received notification '${T.method}'.`,B)}else Xt("receive-notification",T)}function Oi(T,B){if(!(v===yt.Off||!w))if(x===ji.Text){let V;if(v===yt.Verbose&&(T.error&&T.error.data?V=`Error data: ${JSON.stringify(T.error.data,null,4)} + +`:T.result?V=`Result: ${JSON.stringify(T.result,null,4)} + +`:T.error===void 0&&(V=`No result returned. + +`)),B){let te=T.error?` Request failed: ${T.error.message} (${T.error.code}).`:"";w.log(`Received response '${B.method} - (${T.id})' in ${Date.now()-B.timerStart}ms.${te}`,V)}else w.log(`Received response ${T.id} without active response promise.`,V)}else Xt("receive-response",T)}function Xt(T,B){if(!w||v===yt.Off)return;let V={isLSPMessage:!0,type:T,message:B,timestamp:Date.now()};w.log(V)}function qt(){if(Pe())throw new Ws(Gh.Closed,"Connection is closed.");if(We())throw new Ws(Gh.Disposed,"Connection is disposed.")}function Py(){if(ae())throw new Ws(Gh.AlreadyListening,"Connection is already listening")}function Sd(){if(!ae())throw new Error("Call listen() first.")}function Oa(T){return T===void 0?null:T}function MP(T,B){let V,te=T.numberOfParams;switch(te){case 0:V=null;break;case 1:V=Oa(B[0]);break;default:V=[];for(let Qe=0;Qe{qt();let V,te;if(jt.string(T))switch(V=T,B.length){case 0:te=null;break;case 1:te=B[0];break;default:te=B;break}else V=T.method,te=MP(T,B);let Qe={jsonrpc:a,method:V,params:te};ve(Qe),e.write(Qe)},onNotification:(T,B)=>{qt(),jt.func(T)?c=T:B&&(jt.string(T)?f[T]={type:void 0,handler:B}:f[T.method]={type:T,handler:B})},onProgress:(T,B,V)=>{if(p.has(B))throw new Error(`Progress handler for token ${B} already registered`);return p.set(B,V),{dispose:()=>{p.delete(B)}}},sendProgress:(T,B,V)=>{La.sendNotification(zh.type,{token:B,value:V})},onUnhandledProgress:O.event,sendRequest:(T,...B)=>{qt(),Sd();let V,te,Qe;if(jt.string(T))switch(V=T,B.length){case 0:te=null;break;case 1:hl.CancellationToken.is(B[0])?(te=null,Qe=B[0]):te=Oa(B[0]);break;default:let _t=B.length-1;hl.CancellationToken.is(B[_t])?(Qe=B[_t],B.length===2?te=Oa(B[0]):te=B.slice(0,_t).map(tt=>Oa(tt))):te=B.map(tt=>Oa(tt));break}else{V=T.method,te=MP(T,B);let _t=T.numberOfParams;Qe=hl.CancellationToken.is(B[_t])?B[_t]:void 0}let si=n++,ln=new Promise((_t,tt)=>{let hr={jsonrpc:a,id:si,method:V,params:te},rt={method:V,timerStart:Date.now(),resolve:_t,reject:tt};Se(hr);try{e.write(hr)}catch(Zt){rt.reject(new ne.ResponseError(ne.ErrorCodes.MessageWriteError,Zt.message?Zt.message:"Unknown reason")),rt=null}rt&&(m[String(si)]=rt)});return Qe&&Qe.onCancellationRequested(()=>{La.sendNotification(of.type,{id:si})}),ln},onRequest:(T,B)=>{qt(),jt.func(T)?l=T:B&&(jt.string(T)?u[T]={type:void 0,handler:B}:u[T.method]={type:T,handler:B})},trace:(T,B,V)=>{let te=!1,Qe=ji.Text;V!==void 0&&(jt.boolean(V)?te=V:(te=V.sendNotification||!1,Qe=V.traceFormat||ji.Text)),v=T,x=Qe,v===yt.Off?w=void 0:w=B,te&&!Pe()&&!We()&&La.sendNotification(tN.type,{value:yt.toString(T)})},onError:P.event,onClose:k.event,onUnhandledNotification:_.event,onDispose:I.event,dispose:()=>{if(We())return;E=Ui.Disposed,I.fire(void 0);let T=new Error("Connection got disposed.");Object.keys(m).forEach(B=>{m[B].reject(T)}),m=Object.create(null),y=Object.create(null),h=new QM.LinkedMap,jt.func(e.dispose)&&e.dispose(),jt.func(r.dispose)&&r.dispose()},listen:()=>{qt(),Py(),E=Ui.Listening,r.listen(Cy)},inspect:()=>{console.log("inspect")}};return La.onNotification(Uw.type,T=>{v===yt.Off||!w||w.log(T.message,v===yt.Verbose?T.verbose:void 0)}),La.onNotification(zh.type,T=>{let B=p.get(T.token);B?B(T.value):O.fire(T)}),La}function Pse(r){return r.listen!==void 0&&r.read===void 0}function Tse(r){return r.write!==void 0&&r.end===void 0}function Rse(r,e,t,i){t||(t=Q.NullLogger);let n=Pse(r)?r:new rf.StreamMessageReader(r),o=Tse(e)?e:new nf.StreamMessageWriter(e);return _se(n,o,t,i)}Q.createMessageConnection=Rse});var jn=g(kse=>{fo(kse,{CodeAction:()=>hx,CodeActionContext:()=>dx,CodeActionKind:()=>px,CodeLens:()=>mx,Color:()=>Kh,ColorInformation:()=>Hw,ColorPresentation:()=>zw,Command:()=>ml,CompletionItem:()=>tx,CompletionItemKind:()=>Zw,CompletionItemTag:()=>ex,CompletionList:()=>rx,CreateFile:()=>uf,DeleteFile:()=>ff,Diagnostic:()=>sf,DiagnosticRelatedInformation:()=>Jh,DiagnosticSeverity:()=>Kw,DiagnosticTag:()=>Jw,DocumentHighlight:()=>ax,DocumentHighlightKind:()=>sx,DocumentLink:()=>vx,DocumentSymbol:()=>fx,EOL:()=>Fse,FoldingRange:()=>Vw,FoldingRangeKind:()=>Gw,FormattingOptions:()=>gx,Hover:()=>ix,InsertTextFormat:()=>Qw,Location:()=>Vh,LocationLink:()=>Ww,MarkedString:()=>pf,MarkupContent:()=>Zh,MarkupKind:()=>gl,ParameterInformation:()=>nx,Position:()=>Wi,Range:()=>ir,RenameFile:()=>cf,SelectionRange:()=>yx,SignatureInformation:()=>ox,SymbolInformation:()=>cx,SymbolKind:()=>lx,SymbolTag:()=>ux,TextDocument:()=>bx,TextDocumentEdit:()=>af,TextDocumentIdentifier:()=>Yw,TextDocumentItem:()=>Xw,TextEdit:()=>Io,VersionedTextDocumentIdentifier:()=>lf,WorkspaceChange:()=>Ise,WorkspaceEdit:()=>Yh});"use strict";var Wi;(function(r){function e(i,n){return{line:i,character:n}}r.create=e;function t(i){var n=i;return N.objectLiteral(n)&&N.number(n.line)&&N.number(n.character)}r.is=t})(Wi||(Wi={}));var ir;(function(r){function e(i,n,o,s){if(N.number(i)&&N.number(n)&&N.number(o)&&N.number(s))return{start:Wi.create(i,n),end:Wi.create(o,s)};if(Wi.is(i)&&Wi.is(n))return{start:i,end:n};throw new Error("Range#create called with invalid arguments["+i+", "+n+", "+o+", "+s+"]")}r.create=e;function t(i){var n=i;return N.objectLiteral(n)&&Wi.is(n.start)&&Wi.is(n.end)}r.is=t})(ir||(ir={}));var Vh;(function(r){function e(i,n){return{uri:i,range:n}}r.create=e;function t(i){var n=i;return N.defined(n)&&ir.is(n.range)&&(N.string(n.uri)||N.undefined(n.uri))}r.is=t})(Vh||(Vh={}));var Ww;(function(r){function e(i,n,o,s){return{targetUri:i,targetRange:n,targetSelectionRange:o,originSelectionRange:s}}r.create=e;function t(i){var n=i;return N.defined(n)&&ir.is(n.targetRange)&&N.string(n.targetUri)&&(ir.is(n.targetSelectionRange)||N.undefined(n.targetSelectionRange))&&(ir.is(n.originSelectionRange)||N.undefined(n.originSelectionRange))}r.is=t})(Ww||(Ww={}));var Kh;(function(r){function e(i,n,o,s){return{red:i,green:n,blue:o,alpha:s}}r.create=e;function t(i){var n=i;return N.number(n.red)&&N.number(n.green)&&N.number(n.blue)&&N.number(n.alpha)}r.is=t})(Kh||(Kh={}));var Hw;(function(r){function e(i,n){return{range:i,color:n}}r.create=e;function t(i){var n=i;return ir.is(n.range)&&Kh.is(n.color)}r.is=t})(Hw||(Hw={}));var zw;(function(r){function e(i,n,o){return{label:i,textEdit:n,additionalTextEdits:o}}r.create=e;function t(i){var n=i;return N.string(n.label)&&(N.undefined(n.textEdit)||Io.is(n))&&(N.undefined(n.additionalTextEdits)||N.typedArray(n.additionalTextEdits,Io.is))}r.is=t})(zw||(zw={}));var Gw;(function(r){r.Comment="comment",r.Imports="imports",r.Region="region"})(Gw||(Gw={}));var Vw;(function(r){function e(i,n,o,s,a){var l={startLine:i,endLine:n};return N.defined(o)&&(l.startCharacter=o),N.defined(s)&&(l.endCharacter=s),N.defined(a)&&(l.kind=a),l}r.create=e;function t(i){var n=i;return N.number(n.startLine)&&N.number(n.startLine)&&(N.undefined(n.startCharacter)||N.number(n.startCharacter))&&(N.undefined(n.endCharacter)||N.number(n.endCharacter))&&(N.undefined(n.kind)||N.string(n.kind))}r.is=t})(Vw||(Vw={}));var Jh;(function(r){function e(i,n){return{location:i,message:n}}r.create=e;function t(i){var n=i;return N.defined(n)&&Vh.is(n.location)&&N.string(n.message)}r.is=t})(Jh||(Jh={}));var Kw;(function(r){r.Error=1,r.Warning=2,r.Information=3,r.Hint=4})(Kw||(Kw={}));var Jw;(function(r){r.Unnecessary=1,r.Deprecated=2})(Jw||(Jw={}));var sf;(function(r){function e(i,n,o,s,a,l){var u={range:i,message:n};return N.defined(o)&&(u.severity=o),N.defined(s)&&(u.code=s),N.defined(a)&&(u.source=a),N.defined(l)&&(u.relatedInformation=l),u}r.create=e;function t(i){var n=i;return N.defined(n)&&ir.is(n.range)&&N.string(n.message)&&(N.number(n.severity)||N.undefined(n.severity))&&(N.number(n.code)||N.string(n.code)||N.undefined(n.code))&&(N.string(n.source)||N.undefined(n.source))&&(N.undefined(n.relatedInformation)||N.typedArray(n.relatedInformation,Jh.is))}r.is=t})(sf||(sf={}));var ml;(function(r){function e(i,n){for(var o=[],s=2;s0&&(a.arguments=o),a}r.create=e;function t(i){var n=i;return N.defined(n)&&N.string(n.title)&&N.string(n.command)}r.is=t})(ml||(ml={}));var Io;(function(r){function e(o,s){return{range:o,newText:s}}r.replace=e;function t(o,s){return{range:{start:o,end:o},newText:s}}r.insert=t;function i(o){return{range:o,newText:""}}r.del=i;function n(o){var s=o;return N.objectLiteral(s)&&N.string(s.newText)&&ir.is(s.range)}r.is=n})(Io||(Io={}));var af;(function(r){function e(i,n){return{textDocument:i,edits:n}}r.create=e;function t(i){var n=i;return N.defined(n)&&lf.is(n.textDocument)&&Array.isArray(n.edits)}r.is=t})(af||(af={}));var uf;(function(r){function e(i,n){var o={kind:"create",uri:i};return n!==void 0&&(n.overwrite!==void 0||n.ignoreIfExists!==void 0)&&(o.options=n),o}r.create=e;function t(i){var n=i;return n&&n.kind==="create"&&N.string(n.uri)&&(n.options===void 0||(n.options.overwrite===void 0||N.boolean(n.options.overwrite))&&(n.options.ignoreIfExists===void 0||N.boolean(n.options.ignoreIfExists)))}r.is=t})(uf||(uf={}));var cf;(function(r){function e(i,n,o){var s={kind:"rename",oldUri:i,newUri:n};return o!==void 0&&(o.overwrite!==void 0||o.ignoreIfExists!==void 0)&&(s.options=o),s}r.create=e;function t(i){var n=i;return n&&n.kind==="rename"&&N.string(n.oldUri)&&N.string(n.newUri)&&(n.options===void 0||(n.options.overwrite===void 0||N.boolean(n.options.overwrite))&&(n.options.ignoreIfExists===void 0||N.boolean(n.options.ignoreIfExists)))}r.is=t})(cf||(cf={}));var ff;(function(r){function e(i,n){var o={kind:"delete",uri:i};return n!==void 0&&(n.recursive!==void 0||n.ignoreIfNotExists!==void 0)&&(o.options=n),o}r.create=e;function t(i){var n=i;return n&&n.kind==="delete"&&N.string(n.uri)&&(n.options===void 0||(n.options.recursive===void 0||N.boolean(n.options.recursive))&&(n.options.ignoreIfNotExists===void 0||N.boolean(n.options.ignoreIfNotExists)))}r.is=t})(ff||(ff={}));var Yh;(function(r){function e(t){var i=t;return i&&(i.changes!==void 0||i.documentChanges!==void 0)&&(i.documentChanges===void 0||i.documentChanges.every(function(n){return N.string(n.kind)?uf.is(n)||cf.is(n)||ff.is(n):af.is(n)}))}r.is=e})(Yh||(Yh={}));var Xh=function(){function r(e){this.edits=e}return r.prototype.insert=function(e,t){this.edits.push(Io.insert(e,t))},r.prototype.replace=function(e,t){this.edits.push(Io.replace(e,t))},r.prototype.delete=function(e){this.edits.push(Io.del(e))},r.prototype.add=function(e){this.edits.push(e)},r.prototype.all=function(){return this.edits},r.prototype.clear=function(){this.edits.splice(0,this.edits.length)},r}(),Ise=function(){function r(e){var t=this;this._textEditChanges=Object.create(null),e&&(this._workspaceEdit=e,e.documentChanges?e.documentChanges.forEach(function(i){if(af.is(i)){var n=new Xh(i.edits);t._textEditChanges[i.textDocument.uri]=n}}):e.changes&&Object.keys(e.changes).forEach(function(i){var n=new Xh(e.changes[i]);t._textEditChanges[i]=n}))}return Object.defineProperty(r.prototype,"edit",{get:function(){return this._workspaceEdit},enumerable:!0,configurable:!0}),r.prototype.getTextEditChange=function(e){if(lf.is(e)){if(this._workspaceEdit||(this._workspaceEdit={documentChanges:[]}),!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var t=e,i=this._textEditChanges[t.uri];if(!i){var n=[],o={textDocument:t,edits:n};this._workspaceEdit.documentChanges.push(o),i=new Xh(n),this._textEditChanges[t.uri]=i}return i}else{if(this._workspaceEdit||(this._workspaceEdit={changes:Object.create(null)}),!this._workspaceEdit.changes)throw new Error("Workspace edit is not configured for normal text edit changes.");var i=this._textEditChanges[e];if(!i){var n=[];this._workspaceEdit.changes[e]=n,i=new Xh(n),this._textEditChanges[e]=i}return i}},r.prototype.createFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(uf.create(e,t))},r.prototype.renameFile=function(e,t,i){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(cf.create(e,t,i))},r.prototype.deleteFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(ff.create(e,t))},r.prototype.checkDocumentChanges=function(){if(!this._workspaceEdit||!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.")},r}(),Yw;(function(r){function e(i){return{uri:i}}r.create=e;function t(i){var n=i;return N.defined(n)&&N.string(n.uri)}r.is=t})(Yw||(Yw={}));var lf;(function(r){function e(i,n){return{uri:i,version:n}}r.create=e;function t(i){var n=i;return N.defined(n)&&N.string(n.uri)&&(n.version===null||N.number(n.version))}r.is=t})(lf||(lf={}));var Xw;(function(r){function e(i,n,o,s){return{uri:i,languageId:n,version:o,text:s}}r.create=e;function t(i){var n=i;return N.defined(n)&&N.string(n.uri)&&N.string(n.languageId)&&N.number(n.version)&&N.string(n.text)}r.is=t})(Xw||(Xw={}));var gl;(function(r){r.PlainText="plaintext",r.Markdown="markdown"})(gl||(gl={}));(function(r){function e(t){var i=t;return i===r.PlainText||i===r.Markdown}r.is=e})(gl||(gl={}));var Zh;(function(r){function e(t){var i=t;return N.objectLiteral(t)&&gl.is(i.kind)&&N.string(i.value)}r.is=e})(Zh||(Zh={}));var Zw;(function(r){r.Text=1,r.Method=2,r.Function=3,r.Constructor=4,r.Field=5,r.Variable=6,r.Class=7,r.Interface=8,r.Module=9,r.Property=10,r.Unit=11,r.Value=12,r.Enum=13,r.Keyword=14,r.Snippet=15,r.Color=16,r.File=17,r.Reference=18,r.Folder=19,r.EnumMember=20,r.Constant=21,r.Struct=22,r.Event=23,r.Operator=24,r.TypeParameter=25})(Zw||(Zw={}));var Qw;(function(r){r.PlainText=1,r.Snippet=2})(Qw||(Qw={}));var ex;(function(r){r.Deprecated=1})(ex||(ex={}));var tx;(function(r){function e(t){return{label:t}}r.create=e})(tx||(tx={}));var rx;(function(r){function e(t,i){return{items:t||[],isIncomplete:!!i}}r.create=e})(rx||(rx={}));var pf;(function(r){function e(i){return i.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}r.fromPlainText=e;function t(i){var n=i;return N.string(n)||N.objectLiteral(n)&&N.string(n.language)&&N.string(n.value)}r.is=t})(pf||(pf={}));var ix;(function(r){function e(t){var i=t;return!!i&&N.objectLiteral(i)&&(Zh.is(i.contents)||pf.is(i.contents)||N.typedArray(i.contents,pf.is))&&(t.range===void 0||ir.is(t.range))}r.is=e})(ix||(ix={}));var nx;(function(r){function e(t,i){return i?{label:t,documentation:i}:{label:t}}r.create=e})(nx||(nx={}));var ox;(function(r){function e(t,i){for(var n=[],o=2;o=0;c--){var f=l[c],p=o.offsetAt(f.range.start),d=o.offsetAt(f.range.end);if(d<=u)a=a.substring(0,p)+f.newText+a.substring(d,a.length);else throw new Error("Overlapping edit");u=p}return a}r.applyEdits=i;function n(o,s){if(o.length<=1)return o;var a=o.length/2|0,l=o.slice(0,a),u=o.slice(a);n(l,s),n(u,s);for(var c=0,f=0,p=0;c0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets},r.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var t=this.getLineOffsets(),i=0,n=t.length;if(n===0)return Wi.create(0,e);for(;ie?n=o:i=o+1}var s=i-1;return Wi.create(s,e-t[s])},r.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var i=t[e.line],n=e.line+1{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});function Ose(r){return r===!0||r===!1}Hi.boolean=Ose;function rN(r){return typeof r=="string"||r instanceof String}Hi.string=rN;function Lse(r){return typeof r=="number"||r instanceof Number}Hi.number=Lse;function Mse(r){return r instanceof Error}Hi.error=Mse;function Nse(r){return typeof r=="function"}Hi.func=Nse;function iN(r){return Array.isArray(r)}Hi.array=iN;function qse(r){return iN(r)&&r.every(e=>rN(e))}Hi.stringArray=qse;function $se(r,e){return Array.isArray(r)&&r.every(e)}Hi.typedArray=$se;function Bse(r){return r!==null&&typeof r=="object"}Hi.objectLiteral=Bse});var zr=g(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});var Qh=bi(),oN=class extends Qh.RequestType0{constructor(e){super(e)}};vl.ProtocolRequestType0=oN;var sN=class extends Qh.RequestType{constructor(e){super(e)}};vl.ProtocolRequestType=sN;var aN=class extends Qh.NotificationType{constructor(e){super(e)}};vl.ProtocolNotificationType=aN;var lN=class extends Qh.NotificationType0{constructor(e){super(e)}};vl.ProtocolNotificationType0=lN});var uN=g(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var jse=bi(),Use=zr(),Wse;(function(r){r.method="textDocument/implementation",r.type=new Use.ProtocolRequestType(r.method),r.resultType=new jse.ProgressType})(Wse=em.ImplementationRequest||(em.ImplementationRequest={}))});var cN=g(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Hse=bi(),zse=zr(),Gse;(function(r){r.method="textDocument/typeDefinition",r.type=new zse.ProtocolRequestType(r.method),r.resultType=new Hse.ProgressType})(Gse=tm.TypeDefinitionRequest||(tm.TypeDefinitionRequest={}))});var pN=g(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var fN=zr(),Vse;(function(r){r.type=new fN.ProtocolRequestType0("workspace/workspaceFolders")})(Vse=yl.WorkspaceFoldersRequest||(yl.WorkspaceFoldersRequest={}));var Kse;(function(r){r.type=new fN.ProtocolNotificationType("workspace/didChangeWorkspaceFolders")})(Kse=yl.DidChangeWorkspaceFoldersNotification||(yl.DidChangeWorkspaceFoldersNotification={}))});var dN=g(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var Jse=zr(),Yse;(function(r){r.type=new Jse.ProtocolRequestType("workspace/configuration")})(Yse=rm.ConfigurationRequest||(rm.ConfigurationRequest={}))});var mN=g(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var Xse=bi(),hN=zr(),Zse;(function(r){r.method="textDocument/documentColor",r.type=new hN.ProtocolRequestType(r.method),r.resultType=new Xse.ProgressType})(Zse=bl.DocumentColorRequest||(bl.DocumentColorRequest={}));var Qse;(function(r){r.type=new hN.ProtocolRequestType("textDocument/colorPresentation")})(Qse=bl.ColorPresentationRequest||(bl.ColorPresentationRequest={}))});var gN=g(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var eae=bi(),tae=zr(),rae;(function(r){r.Comment="comment",r.Imports="imports",r.Region="region"})(rae=wl.FoldingRangeKind||(wl.FoldingRangeKind={}));var iae;(function(r){r.method="textDocument/foldingRange",r.type=new tae.ProtocolRequestType(r.method),r.resultType=new eae.ProgressType})(iae=wl.FoldingRangeRequest||(wl.FoldingRangeRequest={}))});var vN=g(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var nae=bi(),oae=zr(),sae;(function(r){r.method="textDocument/declaration",r.type=new oae.ProtocolRequestType(r.method),r.resultType=new nae.ProgressType})(sae=im.DeclarationRequest||(im.DeclarationRequest={}))});var yN=g(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var aae=bi(),lae=zr(),uae;(function(r){r.method="textDocument/selectionRange",r.type=new lae.ProtocolRequestType(r.method),r.resultType=new aae.ProgressType})(uae=nm.SelectionRangeRequest||(nm.SelectionRangeRequest={}))});var wN=g(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var cae=bi(),bN=zr(),fae;(function(r){r.type=new cae.ProgressType})(fae=Fo.WorkDoneProgress||(Fo.WorkDoneProgress={}));var pae;(function(r){r.type=new bN.ProtocolRequestType("window/workDoneProgress/create")})(pae=Fo.WorkDoneProgressCreateRequest||(Fo.WorkDoneProgressCreateRequest={}));var dae;(function(r){r.type=new bN.ProtocolNotificationType("window/workDoneProgress/cancel")})(dae=Fo.WorkDoneProgressCancelNotification||(Fo.WorkDoneProgressCancelNotification={}))});var CN=g(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});var Ao=nN(),Un=bi(),pe=zr(),hae=uN();M.ImplementationRequest=hae.ImplementationRequest;var mae=cN();M.TypeDefinitionRequest=mae.TypeDefinitionRequest;var xN=pN();M.WorkspaceFoldersRequest=xN.WorkspaceFoldersRequest;M.DidChangeWorkspaceFoldersNotification=xN.DidChangeWorkspaceFoldersNotification;var gae=dN();M.ConfigurationRequest=gae.ConfigurationRequest;var DN=mN();M.DocumentColorRequest=DN.DocumentColorRequest;M.ColorPresentationRequest=DN.ColorPresentationRequest;var vae=gN();M.FoldingRangeRequest=vae.FoldingRangeRequest;var yae=vN();M.DeclarationRequest=yae.DeclarationRequest;var bae=yN();M.SelectionRangeRequest=bae.SelectionRangeRequest;var wx=wN();M.WorkDoneProgress=wx.WorkDoneProgress;M.WorkDoneProgressCreateRequest=wx.WorkDoneProgressCreateRequest;M.WorkDoneProgressCancelNotification=wx.WorkDoneProgressCancelNotification;var SN;(function(r){function e(t){let i=t;return Ao.string(i.language)||Ao.string(i.scheme)||Ao.string(i.pattern)}r.is=e})(SN=M.DocumentFilter||(M.DocumentFilter={}));var EN;(function(r){function e(t){if(!Array.isArray(t))return!1;for(let i of t)if(!Ao.string(i)&&!SN.is(i))return!1;return!0}r.is=e})(EN=M.DocumentSelector||(M.DocumentSelector={}));var wae;(function(r){r.type=new pe.ProtocolRequestType("client/registerCapability")})(wae=M.RegistrationRequest||(M.RegistrationRequest={}));var xae;(function(r){r.type=new pe.ProtocolRequestType("client/unregisterCapability")})(xae=M.UnregistrationRequest||(M.UnregistrationRequest={}));var Dae;(function(r){r.Create="create",r.Rename="rename",r.Delete="delete"})(Dae=M.ResourceOperationKind||(M.ResourceOperationKind={}));var Sae;(function(r){r.Abort="abort",r.Transactional="transactional",r.TextOnlyTransactional="textOnlyTransactional",r.Undo="undo"})(Sae=M.FailureHandlingKind||(M.FailureHandlingKind={}));var Eae;(function(r){function e(t){let i=t;return i&&Ao.string(i.id)&&i.id.length>0}r.hasId=e})(Eae=M.StaticRegistrationOptions||(M.StaticRegistrationOptions={}));var Cae;(function(r){function e(t){let i=t;return i&&(i.documentSelector===null||EN.is(i.documentSelector))}r.is=e})(Cae=M.TextDocumentRegistrationOptions||(M.TextDocumentRegistrationOptions={}));var _ae;(function(r){function e(i){let n=i;return Ao.objectLiteral(n)&&(n.workDoneProgress===void 0||Ao.boolean(n.workDoneProgress))}r.is=e;function t(i){let n=i;return n&&Ao.boolean(n.workDoneProgress)}r.hasWorkDoneProgress=t})(_ae=M.WorkDoneProgressOptions||(M.WorkDoneProgressOptions={}));var Pae;(function(r){r.type=new pe.ProtocolRequestType("initialize")})(Pae=M.InitializeRequest||(M.InitializeRequest={}));var Tae;(function(r){r.unknownProtocolVersion=1})(Tae=M.InitializeError||(M.InitializeError={}));var Rae;(function(r){r.type=new pe.ProtocolNotificationType("initialized")})(Rae=M.InitializedNotification||(M.InitializedNotification={}));var kae;(function(r){r.type=new pe.ProtocolRequestType0("shutdown")})(kae=M.ShutdownRequest||(M.ShutdownRequest={}));var Iae;(function(r){r.type=new pe.ProtocolNotificationType0("exit")})(Iae=M.ExitNotification||(M.ExitNotification={}));var Fae;(function(r){r.type=new pe.ProtocolNotificationType("workspace/didChangeConfiguration")})(Fae=M.DidChangeConfigurationNotification||(M.DidChangeConfigurationNotification={}));var Aae;(function(r){r.Error=1,r.Warning=2,r.Info=3,r.Log=4})(Aae=M.MessageType||(M.MessageType={}));var Oae;(function(r){r.type=new pe.ProtocolNotificationType("window/showMessage")})(Oae=M.ShowMessageNotification||(M.ShowMessageNotification={}));var Lae;(function(r){r.type=new pe.ProtocolRequestType("window/showMessageRequest")})(Lae=M.ShowMessageRequest||(M.ShowMessageRequest={}));var Mae;(function(r){r.type=new pe.ProtocolNotificationType("window/logMessage")})(Mae=M.LogMessageNotification||(M.LogMessageNotification={}));var Nae;(function(r){r.type=new pe.ProtocolNotificationType("telemetry/event")})(Nae=M.TelemetryEventNotification||(M.TelemetryEventNotification={}));var qae;(function(r){r.None=0,r.Full=1,r.Incremental=2})(qae=M.TextDocumentSyncKind||(M.TextDocumentSyncKind={}));var $ae;(function(r){r.method="textDocument/didOpen",r.type=new pe.ProtocolNotificationType(r.method)})($ae=M.DidOpenTextDocumentNotification||(M.DidOpenTextDocumentNotification={}));var Bae;(function(r){r.method="textDocument/didChange",r.type=new pe.ProtocolNotificationType(r.method)})(Bae=M.DidChangeTextDocumentNotification||(M.DidChangeTextDocumentNotification={}));var jae;(function(r){r.method="textDocument/didClose",r.type=new pe.ProtocolNotificationType(r.method)})(jae=M.DidCloseTextDocumentNotification||(M.DidCloseTextDocumentNotification={}));var Uae;(function(r){r.method="textDocument/didSave",r.type=new pe.ProtocolNotificationType(r.method)})(Uae=M.DidSaveTextDocumentNotification||(M.DidSaveTextDocumentNotification={}));var Wae;(function(r){r.Manual=1,r.AfterDelay=2,r.FocusOut=3})(Wae=M.TextDocumentSaveReason||(M.TextDocumentSaveReason={}));var Hae;(function(r){r.method="textDocument/willSave",r.type=new pe.ProtocolNotificationType(r.method)})(Hae=M.WillSaveTextDocumentNotification||(M.WillSaveTextDocumentNotification={}));var zae;(function(r){r.method="textDocument/willSaveWaitUntil",r.type=new pe.ProtocolRequestType(r.method)})(zae=M.WillSaveTextDocumentWaitUntilRequest||(M.WillSaveTextDocumentWaitUntilRequest={}));var Gae;(function(r){r.type=new pe.ProtocolNotificationType("workspace/didChangeWatchedFiles")})(Gae=M.DidChangeWatchedFilesNotification||(M.DidChangeWatchedFilesNotification={}));var Vae;(function(r){r.Created=1,r.Changed=2,r.Deleted=3})(Vae=M.FileChangeType||(M.FileChangeType={}));var Kae;(function(r){r.Create=1,r.Change=2,r.Delete=4})(Kae=M.WatchKind||(M.WatchKind={}));var Jae;(function(r){r.type=new pe.ProtocolNotificationType("textDocument/publishDiagnostics")})(Jae=M.PublishDiagnosticsNotification||(M.PublishDiagnosticsNotification={}));var Yae;(function(r){r.Invoked=1,r.TriggerCharacter=2,r.TriggerForIncompleteCompletions=3})(Yae=M.CompletionTriggerKind||(M.CompletionTriggerKind={}));var Xae;(function(r){r.method="textDocument/completion",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(Xae=M.CompletionRequest||(M.CompletionRequest={}));var Zae;(function(r){r.method="completionItem/resolve",r.type=new pe.ProtocolRequestType(r.method)})(Zae=M.CompletionResolveRequest||(M.CompletionResolveRequest={}));var Qae;(function(r){r.method="textDocument/hover",r.type=new pe.ProtocolRequestType(r.method)})(Qae=M.HoverRequest||(M.HoverRequest={}));var ele;(function(r){r.Invoked=1,r.TriggerCharacter=2,r.ContentChange=3})(ele=M.SignatureHelpTriggerKind||(M.SignatureHelpTriggerKind={}));var tle;(function(r){r.method="textDocument/signatureHelp",r.type=new pe.ProtocolRequestType(r.method)})(tle=M.SignatureHelpRequest||(M.SignatureHelpRequest={}));var rle;(function(r){r.method="textDocument/definition",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(rle=M.DefinitionRequest||(M.DefinitionRequest={}));var ile;(function(r){r.method="textDocument/references",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(ile=M.ReferencesRequest||(M.ReferencesRequest={}));var nle;(function(r){r.method="textDocument/documentHighlight",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(nle=M.DocumentHighlightRequest||(M.DocumentHighlightRequest={}));var ole;(function(r){r.method="textDocument/documentSymbol",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(ole=M.DocumentSymbolRequest||(M.DocumentSymbolRequest={}));var sle;(function(r){r.method="textDocument/codeAction",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(sle=M.CodeActionRequest||(M.CodeActionRequest={}));var ale;(function(r){r.method="workspace/symbol",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(ale=M.WorkspaceSymbolRequest||(M.WorkspaceSymbolRequest={}));var lle;(function(r){r.type=new pe.ProtocolRequestType("textDocument/codeLens"),r.resultType=new Un.ProgressType})(lle=M.CodeLensRequest||(M.CodeLensRequest={}));var ule;(function(r){r.type=new pe.ProtocolRequestType("codeLens/resolve")})(ule=M.CodeLensResolveRequest||(M.CodeLensResolveRequest={}));var cle;(function(r){r.method="textDocument/documentLink",r.type=new pe.ProtocolRequestType(r.method),r.resultType=new Un.ProgressType})(cle=M.DocumentLinkRequest||(M.DocumentLinkRequest={}));var fle;(function(r){r.type=new pe.ProtocolRequestType("documentLink/resolve")})(fle=M.DocumentLinkResolveRequest||(M.DocumentLinkResolveRequest={}));var ple;(function(r){r.method="textDocument/formatting",r.type=new pe.ProtocolRequestType(r.method)})(ple=M.DocumentFormattingRequest||(M.DocumentFormattingRequest={}));var dle;(function(r){r.method="textDocument/rangeFormatting",r.type=new pe.ProtocolRequestType(r.method)})(dle=M.DocumentRangeFormattingRequest||(M.DocumentRangeFormattingRequest={}));var hle;(function(r){r.method="textDocument/onTypeFormatting",r.type=new pe.ProtocolRequestType(r.method)})(hle=M.DocumentOnTypeFormattingRequest||(M.DocumentOnTypeFormattingRequest={}));var mle;(function(r){r.method="textDocument/rename",r.type=new pe.ProtocolRequestType(r.method)})(mle=M.RenameRequest||(M.RenameRequest={}));var gle;(function(r){r.method="textDocument/prepareRename",r.type=new pe.ProtocolRequestType(r.method)})(gle=M.PrepareRenameRequest||(M.PrepareRenameRequest={}));var vle;(function(r){r.type=new pe.ProtocolRequestType("workspace/executeCommand")})(vle=M.ExecuteCommandRequest||(M.ExecuteCommandRequest={}));var yle;(function(r){r.type=new pe.ProtocolRequestType("workspace/applyEdit")})(yle=M.ApplyWorkspaceEditRequest||(M.ApplyWorkspaceEditRequest={}))});var _N=g(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var xx=zr(),ble;(function(r){r.method="textDocument/prepareCallHierarchy",r.type=new xx.ProtocolRequestType(r.method)})(ble=Oo.CallHierarchyPrepareRequest||(Oo.CallHierarchyPrepareRequest={}));var wle;(function(r){r.method="callHierarchy/incomingCalls",r.type=new xx.ProtocolRequestType(r.method)})(wle=Oo.CallHierarchyIncomingCallsRequest||(Oo.CallHierarchyIncomingCallsRequest={}));var xle;(function(r){r.method="callHierarchy/outgoingCalls",r.type=new xx.ProtocolRequestType(r.method)})(xle=Oo.CallHierarchyOutgoingCallsRequest||(Oo.CallHierarchyOutgoingCallsRequest={}))});var PN=g(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});var Dx=zr(),Dle;(function(r){r.comment="comment",r.keyword="keyword",r.string="string",r.number="number",r.regexp="regexp",r.operator="operator",r.namespace="namespace",r.type="type",r.struct="struct",r.class="class",r.interface="interface",r.enum="enum",r.typeParameter="typeParameter",r.function="function",r.member="member",r.property="property",r.macro="macro",r.variable="variable",r.parameter="parameter",r.label="label"})(Dle=Rr.SemanticTokenTypes||(Rr.SemanticTokenTypes={}));var Sle;(function(r){r.documentation="documentation",r.declaration="declaration",r.definition="definition",r.reference="reference",r.static="static",r.abstract="abstract",r.deprecated="deprecated",r.async="async",r.volatile="volatile",r.readonly="readonly"})(Sle=Rr.SemanticTokenModifiers||(Rr.SemanticTokenModifiers={}));var Ele;(function(r){function e(t){let i=t;return i!==void 0&&(i.resultId===void 0||typeof i.resultId=="string")&&Array.isArray(i.data)&&(i.data.length===0||typeof i.data[0]=="number")}r.is=e})(Ele=Rr.SemanticTokens||(Rr.SemanticTokens={}));var Cle;(function(r){r.method="textDocument/semanticTokens",r.type=new Dx.ProtocolRequestType(r.method)})(Cle=Rr.SemanticTokensRequest||(Rr.SemanticTokensRequest={}));var _le;(function(r){r.method="textDocument/semanticTokens/edits",r.type=new Dx.ProtocolRequestType(r.method)})(_le=Rr.SemanticTokensEditsRequest||(Rr.SemanticTokensEditsRequest={}));var Ple;(function(r){r.method="textDocument/semanticTokens/range",r.type=new Dx.ProtocolRequestType(r.method)})(Ple=Rr.SemanticTokensRangeRequest||(Rr.SemanticTokensRangeRequest={}))});var W=g(_e=>{"use strict";function TN(r){for(var e in r)_e.hasOwnProperty(e)||(_e[e]=r[e])}Object.defineProperty(_e,"__esModule",{value:!0});var je=bi();_e.ErrorCodes=je.ErrorCodes;_e.ResponseError=je.ResponseError;_e.CancellationToken=je.CancellationToken;_e.CancellationTokenSource=je.CancellationTokenSource;_e.Disposable=je.Disposable;_e.Event=je.Event;_e.Emitter=je.Emitter;_e.Trace=je.Trace;_e.TraceFormat=je.TraceFormat;_e.SetTraceNotification=je.SetTraceNotification;_e.LogTraceNotification=je.LogTraceNotification;_e.RequestType=je.RequestType;_e.RequestType0=je.RequestType0;_e.NotificationType=je.NotificationType;_e.NotificationType0=je.NotificationType0;_e.MessageReader=je.MessageReader;_e.MessageWriter=je.MessageWriter;_e.ConnectionStrategy=je.ConnectionStrategy;_e.StreamMessageReader=je.StreamMessageReader;_e.StreamMessageWriter=je.StreamMessageWriter;_e.IPCMessageReader=je.IPCMessageReader;_e.IPCMessageWriter=je.IPCMessageWriter;_e.createClientPipeTransport=je.createClientPipeTransport;_e.createServerPipeTransport=je.createServerPipeTransport;_e.generateRandomPipeName=je.generateRandomPipeName;_e.createClientSocketTransport=je.createClientSocketTransport;_e.createServerSocketTransport=je.createServerSocketTransport;_e.ProgressType=je.ProgressType;TN(jn());TN(CN());var xl=_N(),Wn=PN(),Tle;(function(r){let e;(function(a){a.method=xl.CallHierarchyPrepareRequest.method,a.type=xl.CallHierarchyPrepareRequest.type})(e=r.CallHierarchyPrepareRequest||(r.CallHierarchyPrepareRequest={}));let t;(function(a){a.method=xl.CallHierarchyIncomingCallsRequest.method,a.type=xl.CallHierarchyIncomingCallsRequest.type})(t=r.CallHierarchyIncomingCallsRequest||(r.CallHierarchyIncomingCallsRequest={}));let i;(function(a){a.method=xl.CallHierarchyOutgoingCallsRequest.method,a.type=xl.CallHierarchyOutgoingCallsRequest.type})(i=r.CallHierarchyOutgoingCallsRequest||(r.CallHierarchyOutgoingCallsRequest={})),r.SemanticTokenTypes=Wn.SemanticTokenTypes,r.SemanticTokenModifiers=Wn.SemanticTokenModifiers,r.SemanticTokens=Wn.SemanticTokens;let n;(function(a){a.method=Wn.SemanticTokensRequest.method,a.type=Wn.SemanticTokensRequest.type})(n=r.SemanticTokensRequest||(r.SemanticTokensRequest={}));let o;(function(a){a.method=Wn.SemanticTokensEditsRequest.method,a.type=Wn.SemanticTokensEditsRequest.type})(o=r.SemanticTokensEditsRequest||(r.SemanticTokensEditsRequest={}));let s;(function(a){a.method=Wn.SemanticTokensRangeRequest.method,a.type=Wn.SemanticTokensRangeRequest.type})(s=r.SemanticTokensRangeRequest||(r.SemanticTokensRangeRequest={}))})(Tle=_e.Proposed||(_e.Proposed={}));function Rle(r,e,t,i){return je.createMessageConnection(r,e,t,i)}_e.createProtocolConnection=Rle});var Gr=g((ePe,RN)=>{function Sx(r,e,t){var i,n,o,s,a;e==null&&(e=100);function l(){var c=Date.now()-s;c=0?i=setTimeout(l,e-c):(i=null,t||(a=r.apply(o,n),o=n=null))}var u=function(){o=this,n=arguments,s=Date.now();var c=t&&!i;return i||(i=setTimeout(l,e)),c&&(a=r.apply(o,n),o=n=null),a};return u.clear=function(){i&&(clearTimeout(i),i=null)},u.flush=function(){i&&(a=r.apply(o,n),o=n=null,clearTimeout(i),i=null)},u}Sx.debounce=Sx;RN.exports=Sx});var IN=g((tPe,kN)=>{"use strict";var lt={rfc3986:{}};lt.generate=function(){var r="|",e="0-9",t="["+e+"]",i="a-zA-Z",n="["+i+"]";lt.rfc3986.cidr=t+r+"[1-2]"+t+r+"3[0-2]";var o=e+"A-Fa-f",s="["+o+"]",a=i+e+"-\\._~",l="!\\$&'\\(\\)\\*\\+,;=",u="%"+o,c=a+u+l+":@",f="["+c+"]",p="0?",d="(?:"+p+p+t+r+p+"[1-9]"+t+r+"1"+t+t+r+"2[0-4]"+t+r+"25[0-5])";lt.rfc3986.IPv4address="(?:"+d+"\\.){3}"+d;var h=s+"{1,4}",m="(?:"+h+":"+h+"|"+lt.rfc3986.IPv4address+")",y="(?:"+h+":){6}"+m,v="::(?:"+h+":){5}"+m,x="(?:"+h+")?::(?:"+h+":){4}"+m,w="(?:(?:"+h+":){0,1}"+h+")?::(?:"+h+":){3}"+m,E="(?:(?:"+h+":){0,2}"+h+")?::(?:"+h+":){2}"+m,P="(?:(?:"+h+":){0,3}"+h+")?::"+h+":"+m,k="(?:(?:"+h+":){0,4}"+h+")?::"+m,_="(?:(?:"+h+":){0,5}"+h+")?::"+h,O="(?:(?:"+h+":){0,6}"+h+")?::";lt.rfc3986.IPv6address="(?:"+y+r+v+r+x+r+w+r+E+r+P+r+k+r+_+r+O+")",lt.rfc3986.IPvFuture="v"+s+"+\\.["+a+l+":]+",lt.rfc3986.scheme=n+"["+i+e+"+-\\.]*";var I="["+a+u+l+":]*";lt.rfc3986.IPLiteral="\\[(?:"+lt.rfc3986.IPv6address+r+lt.rfc3986.IPvFuture+")\\]";var L="["+a+u+l+"]{0,255}",R="(?:"+lt.rfc3986.IPLiteral+r+lt.rfc3986.IPv4address+r+L+")",F=t+"*",q="(?:"+I+"@)?"+R+"(?::"+F+")?",K=f+"*",ae=f+"+",Pe="(?:\\/"+K+")*",We="\\/(?:"+ae+Pe+")?",Yt=ae+Pe;lt.rfc3986.hierPart="(?:(?:\\/\\/"+q+Pe+")"+r+We+r+Yt+")",lt.rfc3986.query="["+c+"\\/\\?]*(?=#|$)",lt.rfc3986.fragment="["+c+"\\/\\?]*",lt.rfc3986.uri="^(?:"+lt.rfc3986.scheme+":"+lt.rfc3986.hierPart+")(?:\\?"+lt.rfc3986.query+")?(?:#"+lt.rfc3986.fragment+")?$"};lt.generate();kN.exports=lt.rfc3986});var Ex=g((rPe,FN)=>{"use strict";var df=IN();function kle(r){return r.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}var hf={Uri:{createUriRegex:function(r){if(r=r||{},typeof r!="object"||Array.isArray(r))throw new Error("options must be an object");var e="";if(r.scheme){if(Array.isArray(r.scheme)||(r.scheme=[r.scheme]),r.scheme.length<=0)throw new Error("scheme must have at least 1 scheme specified");for(var t=0;t{BN.exports=jN;jN.sync=Ble;var UN=require("fs");function jle(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i{zN.exports=GN;GN.sync=Ule;var VN=require("fs");function GN(r,e,t){VN.stat(r,function(i,n){t(i,i?!1:KN(n,e))})}function Ule(r,e){return KN(VN.statSync(r),e)}function KN(r,e){return r.isFile()&&Wle(r,e)}function Wle(r,e){var t=r.mode,i=r.uid,n=r.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),u=parseInt("001",8),c=a|l,f=t&u||t&l&&n===s||t&a&&i===o||t&c&&o===0;return f}});var XN=g((aPe,YN)=>{var sPe=require("fs"),sm;process.platform==="win32"||global.TESTING_WINDOWS?sm=HN():sm=JN();YN.exports=_x;_x.sync=Hle;function _x(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,n){_x(r,e||{},function(o,s){o?n(o):i(s)})})}sm(r,e||{},function(i,n){i&&(i.code==="EACCES"||e&&e.ignoreErrors)&&(i=null,n=!1),t(i,n)})}function Hle(r,e){try{return sm.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var El=g((lPe,ZN)=>{var Sl=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",QN=require("path"),zle=Sl?";":":",eq=XN(),tq=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),rq=(r,e)=>{let t=e.colon||zle,i=r.match(/\//)||Sl&&r.match(/\\/)?[""]:[...Sl?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=Sl?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=Sl?n.split(t):[""];return Sl&&r.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:i,pathExt:o,pathExtExe:n}},iq=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:i,pathExt:n,pathExtExe:o}=rq(r,e),s=[],a=u=>new Promise((c,f)=>{if(u===i.length)return e.all&&s.length?c(s):f(tq(r));let p=i[u],d=/^".*"$/.test(p)?p.slice(1,-1):p,h=QN.join(d,r),m=!d&&/^\.[\\\/]/.test(r)?r.slice(0,2)+h:h;c(l(m,u,0))}),l=(u,c,f)=>new Promise((p,d)=>{if(f===n.length)return p(a(c+1));let h=n[f];eq(u+h,{pathExt:o},(m,y)=>{if(!m&&y)if(e.all)s.push(u+h);else return p(u+h);return p(l(u,c,f+1))})});return t?a(0).then(u=>t(null,u),t):a(0)},Gle=(r,e)=>{e=e||{};let{pathEnv:t,pathExt:i,pathExtExe:n}=rq(r,e),o=[];for(let s=0;s{var nue="2.0.0",oue=256,sue=Number.MAX_SAFE_INTEGER||9007199254740991,aue=16;hq.exports={SEMVER_SPEC_VERSION:nue,MAX_LENGTH:oue,MAX_SAFE_INTEGER:sue,MAX_SAFE_COMPONENT_LENGTH:aue}});var bf=g((xPe,mq)=>{var lue=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};mq.exports=lue});var zs=g((Mo,gq)=>{var{MAX_SAFE_COMPONENT_LENGTH:Lx}=yf(),uue=bf();Mo=gq.exports={};var cue=Mo.re=[],Y=Mo.src=[],X=Mo.t={},fue=0,de=(r,e,t)=>{let i=fue++;uue(i,e),X[r]=i,Y[i]=e,cue[i]=new RegExp(e,t?"g":void 0)};de("NUMERICIDENTIFIER","0|[1-9]\\d*");de("NUMERICIDENTIFIERLOOSE","[0-9]+");de("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*");de("MAINVERSION",`(${Y[X.NUMERICIDENTIFIER]})\\.(${Y[X.NUMERICIDENTIFIER]})\\.(${Y[X.NUMERICIDENTIFIER]})`);de("MAINVERSIONLOOSE",`(${Y[X.NUMERICIDENTIFIERLOOSE]})\\.(${Y[X.NUMERICIDENTIFIERLOOSE]})\\.(${Y[X.NUMERICIDENTIFIERLOOSE]})`);de("PRERELEASEIDENTIFIER",`(?:${Y[X.NUMERICIDENTIFIER]}|${Y[X.NONNUMERICIDENTIFIER]})`);de("PRERELEASEIDENTIFIERLOOSE",`(?:${Y[X.NUMERICIDENTIFIERLOOSE]}|${Y[X.NONNUMERICIDENTIFIER]})`);de("PRERELEASE",`(?:-(${Y[X.PRERELEASEIDENTIFIER]}(?:\\.${Y[X.PRERELEASEIDENTIFIER]})*))`);de("PRERELEASELOOSE",`(?:-?(${Y[X.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Y[X.PRERELEASEIDENTIFIERLOOSE]})*))`);de("BUILDIDENTIFIER","[0-9A-Za-z-]+");de("BUILD",`(?:\\+(${Y[X.BUILDIDENTIFIER]}(?:\\.${Y[X.BUILDIDENTIFIER]})*))`);de("FULLPLAIN",`v?${Y[X.MAINVERSION]}${Y[X.PRERELEASE]}?${Y[X.BUILD]}?`);de("FULL",`^${Y[X.FULLPLAIN]}$`);de("LOOSEPLAIN",`[v=\\s]*${Y[X.MAINVERSIONLOOSE]}${Y[X.PRERELEASELOOSE]}?${Y[X.BUILD]}?`);de("LOOSE",`^${Y[X.LOOSEPLAIN]}$`);de("GTLT","((?:<|>)?=?)");de("XRANGEIDENTIFIERLOOSE",`${Y[X.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);de("XRANGEIDENTIFIER",`${Y[X.NUMERICIDENTIFIER]}|x|X|\\*`);de("XRANGEPLAIN",`[v=\\s]*(${Y[X.XRANGEIDENTIFIER]})(?:\\.(${Y[X.XRANGEIDENTIFIER]})(?:\\.(${Y[X.XRANGEIDENTIFIER]})(?:${Y[X.PRERELEASE]})?${Y[X.BUILD]}?)?)?`);de("XRANGEPLAINLOOSE",`[v=\\s]*(${Y[X.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[X.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[X.XRANGEIDENTIFIERLOOSE]})(?:${Y[X.PRERELEASELOOSE]})?${Y[X.BUILD]}?)?)?`);de("XRANGE",`^${Y[X.GTLT]}\\s*${Y[X.XRANGEPLAIN]}$`);de("XRANGELOOSE",`^${Y[X.GTLT]}\\s*${Y[X.XRANGEPLAINLOOSE]}$`);de("COERCE",`(^|[^\\d])(\\d{1,${Lx}})(?:\\.(\\d{1,${Lx}}))?(?:\\.(\\d{1,${Lx}}))?(?:$|[^\\d])`);de("COERCERTL",Y[X.COERCE],!0);de("LONETILDE","(?:~>?)");de("TILDETRIM",`(\\s*)${Y[X.LONETILDE]}\\s+`,!0);Mo.tildeTrimReplace="$1~";de("TILDE",`^${Y[X.LONETILDE]}${Y[X.XRANGEPLAIN]}$`);de("TILDELOOSE",`^${Y[X.LONETILDE]}${Y[X.XRANGEPLAINLOOSE]}$`);de("LONECARET","(?:\\^)");de("CARETTRIM",`(\\s*)${Y[X.LONECARET]}\\s+`,!0);Mo.caretTrimReplace="$1^";de("CARET",`^${Y[X.LONECARET]}${Y[X.XRANGEPLAIN]}$`);de("CARETLOOSE",`^${Y[X.LONECARET]}${Y[X.XRANGEPLAINLOOSE]}$`);de("COMPARATORLOOSE",`^${Y[X.GTLT]}\\s*(${Y[X.LOOSEPLAIN]})$|^$`);de("COMPARATOR",`^${Y[X.GTLT]}\\s*(${Y[X.FULLPLAIN]})$|^$`);de("COMPARATORTRIM",`(\\s*)${Y[X.GTLT]}\\s*(${Y[X.LOOSEPLAIN]}|${Y[X.XRANGEPLAIN]})`,!0);Mo.comparatorTrimReplace="$1$2$3";de("HYPHENRANGE",`^\\s*(${Y[X.XRANGEPLAIN]})\\s+-\\s+(${Y[X.XRANGEPLAIN]})\\s*$`);de("HYPHENRANGELOOSE",`^\\s*(${Y[X.XRANGEPLAINLOOSE]})\\s+-\\s+(${Y[X.XRANGEPLAINLOOSE]})\\s*$`);de("STAR","(<|>)?=?\\s*\\*");de("GTE0","^\\s*>=\\s*0.0.0\\s*$");de("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")});var pm=g((DPe,vq)=>{var yq=/^[0-9]+$/,bq=(r,e)=>{let t=yq.test(r),i=yq.test(e);return t&&i&&(r=+r,e=+e),r===e?0:t&&!i?-1:i&&!t?1:rbq(e,r);vq.exports={compareIdentifiers:bq,rcompareIdentifiers:pue}});var nr=g((SPe,wq)=>{var dm=bf(),{MAX_LENGTH:xq,MAX_SAFE_INTEGER:hm}=yf(),{re:Dq,t:Sq}=zs(),{compareIdentifiers:wf}=pm(),wi=class{constructor(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof wi){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid Version: ${e}`);if(e.length>xq)throw new TypeError(`version is longer than ${xq} characters`);dm("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?Dq[Sq.LOOSE]:Dq[Sq.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>hm||this.major<0)throw new TypeError("Invalid major version");if(this.minor>hm||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>hm||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let o=+n;if(o>=0&&o=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);i===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error(`invalid increment argument: ${e}`)}return this.format(),this.raw=this.version,this}};wq.exports=wi});var Gs=g((EPe,Eq)=>{var{MAX_LENGTH:due}=yf(),{re:Cq,t:_q}=zs(),Pq=nr(),hue=(r,e)=>{if((!e||typeof e!="object")&&(e={loose:!!e,includePrerelease:!1}),r instanceof Pq)return r;if(typeof r!="string"||r.length>due||!(e.loose?Cq[_q.LOOSE]:Cq[_q.FULL]).test(r))return null;try{return new Pq(r,e)}catch(i){return null}};Eq.exports=hue});var Rq=g((CPe,Tq)=>{var mue=Gs(),gue=(r,e)=>{let t=mue(r,e);return t?t.version:null};Tq.exports=gue});var Iq=g((_Pe,kq)=>{var vue=Gs(),yue=(r,e)=>{let t=vue(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};kq.exports=yue});var Aq=g((PPe,Fq)=>{var bue=nr(),wue=(r,e,t,i)=>{typeof t=="string"&&(i=t,t=void 0);try{return new bue(r,t).inc(e,i).version}catch(n){return null}};Fq.exports=wue});var xi=g((TPe,Oq)=>{var Lq=nr(),xue=(r,e,t)=>new Lq(r,t).compare(new Lq(e,t));Oq.exports=xue});var mm=g((RPe,Mq)=>{var Due=xi(),Sue=(r,e,t)=>Due(r,e,t)===0;Mq.exports=Sue});var $q=g((kPe,Nq)=>{var qq=Gs(),Eue=mm(),Cue=(r,e)=>{if(Eue(r,e))return null;{let t=qq(r),i=qq(e),n=t.prerelease.length||i.prerelease.length,o=n?"pre":"",s=n?"prerelease":"";for(let a in t)if((a==="major"||a==="minor"||a==="patch")&&t[a]!==i[a])return o+a;return s}};Nq.exports=Cue});var jq=g((IPe,Bq)=>{var _ue=nr(),Pue=(r,e)=>new _ue(r,e).major;Bq.exports=Pue});var Wq=g((FPe,Uq)=>{var Tue=nr(),Rue=(r,e)=>new Tue(r,e).minor;Uq.exports=Rue});var zq=g((APe,Hq)=>{var kue=nr(),Iue=(r,e)=>new kue(r,e).patch;Hq.exports=Iue});var Vq=g((OPe,Gq)=>{var Fue=Gs(),Aue=(r,e)=>{let t=Fue(r,e);return t&&t.prerelease.length?t.prerelease:null};Gq.exports=Aue});var Jq=g((LPe,Kq)=>{var Oue=xi(),Lue=(r,e,t)=>Oue(e,r,t);Kq.exports=Lue});var Xq=g((MPe,Yq)=>{var Mue=xi(),Nue=(r,e)=>Mue(r,e,!0);Yq.exports=Nue});var gm=g((NPe,Zq)=>{var Qq=nr(),que=(r,e,t)=>{let i=new Qq(r,t),n=new Qq(e,t);return i.compare(n)||i.compareBuild(n)};Zq.exports=que});var t2=g((qPe,e2)=>{var $ue=gm(),Bue=(r,e)=>r.sort((t,i)=>$ue(t,i,e));e2.exports=Bue});var i2=g(($Pe,r2)=>{var jue=gm(),Uue=(r,e)=>r.sort((t,i)=>jue(i,t,e));r2.exports=Uue});var xf=g((BPe,n2)=>{var Wue=xi(),Hue=(r,e,t)=>Wue(r,e,t)>0;n2.exports=Hue});var vm=g((jPe,o2)=>{var zue=xi(),Gue=(r,e,t)=>zue(r,e,t)<0;o2.exports=Gue});var Mx=g((UPe,s2)=>{var Vue=xi(),Kue=(r,e,t)=>Vue(r,e,t)!==0;s2.exports=Kue});var ym=g((WPe,a2)=>{var Jue=xi(),Yue=(r,e,t)=>Jue(r,e,t)>=0;a2.exports=Yue});var bm=g((HPe,l2)=>{var Xue=xi(),Zue=(r,e,t)=>Xue(r,e,t)<=0;l2.exports=Zue});var Nx=g((zPe,u2)=>{var Que=mm(),ece=Mx(),tce=xf(),rce=ym(),ice=vm(),nce=bm(),oce=(r,e,t,i)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Que(r,t,i);case"!=":return ece(r,t,i);case">":return tce(r,t,i);case">=":return rce(r,t,i);case"<":return ice(r,t,i);case"<=":return nce(r,t,i);default:throw new TypeError(`Invalid operator: ${e}`)}};u2.exports=oce});var f2=g((GPe,c2)=>{var sce=nr(),ace=Gs(),{re:wm,t:xm}=zs(),lce=(r,e)=>{if(r instanceof sce)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(wm[xm.COERCE]);else{let i;for(;(i=wm[xm.COERCERTL].exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||i.index+i[0].length!==t.index+t[0].length)&&(t=i),wm[xm.COERCERTL].lastIndex=i.index+i[1].length+i[2].length;wm[xm.COERCERTL].lastIndex=-1}return t===null?null:ace(`${t[2]}.${t[3]||"0"}.${t[4]||"0"}`,e)};c2.exports=lce});var Di=g((VPe,p2)=>{var Rl=class{constructor(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof Rl)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new Rl(e.raw,t);if(e instanceof qx)return this.raw=e.value,this.set=[[e]],this.format(),this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${e}`);this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){let t=this.options.loose;e=e.trim();let i=t?or[Ut.HYPHENRANGELOOSE]:or[Ut.HYPHENRANGE];e=e.replace(i,mce(this.options.includePrerelease)),ft("hyphen replace",e),e=e.replace(or[Ut.COMPARATORTRIM],cce),ft("comparator trim",e,or[Ut.COMPARATORTRIM]),e=e.replace(or[Ut.TILDETRIM],fce),e=e.replace(or[Ut.CARETTRIM],pce),e=e.split(/\s+/).join(" ");let n=t?or[Ut.COMPARATORLOOSE]:or[Ut.COMPARATOR];return e.split(" ").map(o=>dce(o,this.options)).join(" ").split(/\s+/).map(o=>hce(o,this.options)).filter(this.options.loose?o=>!!o.match(n):()=>!0).map(o=>new qx(o,this.options))}intersects(e,t){if(!(e instanceof Rl))throw new TypeError("a Range is required");return this.set.some(i=>d2(i,t)&&e.set.some(n=>d2(n,t)&&i.every(o=>n.every(s=>o.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new uce(e,this.options)}catch(t){return!1}for(let t=0;t{let t=!0,i=r.slice(),n=i.pop();for(;t&&i.length;)t=i.every(o=>n.intersects(o,e)),n=i.pop();return t},dce=(r,e)=>(ft("comp",r,e),r=yce(r,e),ft("caret",r),r=vce(r,e),ft("tildes",r),r=bce(r,e),ft("xrange",r),r=wce(r,e),ft("stars",r),r),br=r=>!r||r.toLowerCase()==="x"||r==="*",vce=(r,e)=>r.trim().split(/\s+/).map(t=>xce(t,e)).join(" "),xce=(r,e)=>{let t=e.loose?or[Ut.TILDELOOSE]:or[Ut.TILDE];return r.replace(t,(i,n,o,s,a)=>{ft("tilde",r,i,n,o,s,a);let l;return br(n)?l="":br(o)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:br(s)?l=`>=${n}.${o}.0 <${n}.${+o+1}.0-0`:a?(ft("replaceTilde pr",a),l=`>=${n}.${o}.${s}-${a} <${n}.${+o+1}.0-0`):l=`>=${n}.${o}.${s} <${n}.${+o+1}.0-0`,ft("tilde return",l),l})},yce=(r,e)=>r.trim().split(/\s+/).map(t=>Dce(t,e)).join(" "),Dce=(r,e)=>{ft("caret",r,e);let t=e.loose?or[Ut.CARETLOOSE]:or[Ut.CARET],i=e.includePrerelease?"-0":"";return r.replace(t,(n,o,s,a,l)=>{ft("caret",r,n,o,s,a,l);let u;return br(o)?u="":br(s)?u=`>=${o}.0.0${i} <${+o+1}.0.0-0`:br(a)?o==="0"?u=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:l?(ft("replaceCaret pr",l),o==="0"?s==="0"?u=`>=${o}.${s}.${a}-${l} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}-${l} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a}-${l} <${+o+1}.0.0-0`):(ft("no pr"),o==="0"?s==="0"?u=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),ft("caret return",u),u})},bce=(r,e)=>(ft("replaceXRanges",r,e),r.split(/\s+/).map(t=>Sce(t,e)).join(" ")),Sce=(r,e)=>{r=r.trim();let t=e.loose?or[Ut.XRANGELOOSE]:or[Ut.XRANGE];return r.replace(t,(i,n,o,s,a,l)=>{ft("xRange",r,i,n,o,s,a,l);let u=br(o),c=u||br(s),f=c||br(a),p=f;return n==="="&&p&&(n=""),l=e.includePrerelease?"-0":"",u?n===">"||n==="<"?i="<0.0.0-0":i="*":n&&p?(c&&(s=0),a=0,n===">"?(n=">=",c?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):n==="<="&&(n="<",c?o=+o+1:s=+s+1),n==="<"&&(l="-0"),i=`${n+o}.${s}.${a}${l}`):c?i=`>=${o}.0.0${l} <${+o+1}.0.0-0`:f&&(i=`>=${o}.${s}.0${l} <${o}.${+s+1}.0-0`),ft("xRange return",i),i})},wce=(r,e)=>(ft("replaceStars",r,e),r.trim().replace(or[Ut.STAR],"")),hce=(r,e)=>(ft("replaceGTE0",r,e),r.trim().replace(or[e.includePrerelease?Ut.GTE0PRE:Ut.GTE0],"")),mce=r=>(e,t,i,n,o,s,a,l,u,c,f,p,d)=>(br(i)?t="":br(n)?t=`>=${i}.0.0${r?"-0":""}`:br(o)?t=`>=${i}.${n}.0${r?"-0":""}`:s?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,br(u)?l="":br(c)?l=`<${+u+1}.0.0-0`:br(f)?l=`<${u}.${+c+1}.0-0`:p?l=`<=${u}.${c}.${f}-${p}`:r?l=`<${u}.${c}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),gce=(r,e,t)=>{for(let i=0;i0){let n=r[i].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Df=g((KPe,h2)=>{var Sf=Symbol("SemVer ANY"),Ef=class{static get ANY(){return Sf}constructor(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof Ef){if(e.loose===!!t.loose)return e;e=e.value}Bx("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Sf?this.value="":this.value=this.operator+this.semver.version,Bx("comp",this)}parse(e){let t=this.options.loose?m2[g2.COMPARATORLOOSE]:m2[g2.COMPARATOR],i=e.match(t);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new v2(i[2],this.options.loose):this.semver=Sf}toString(){return this.value}test(e){if(Bx("Comparator.test",e,this.options.loose),this.semver===Sf||e===Sf)return!0;if(typeof e=="string")try{e=new v2(e,this.options)}catch(t){return!1}return $x(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Ef))throw new TypeError("a Comparator is required");if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),this.operator==="")return this.value===""?!0:new y2(e.value,t).test(this.value);if(e.operator==="")return e.value===""?!0:new y2(this.value,t).test(e.semver);let i=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),o=this.semver.version===e.semver.version,s=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),a=$x(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=$x(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return i||n||o&&s||a||l}};h2.exports=Ef;var{re:m2,t:g2}=zs(),$x=Nx(),Bx=bf(),v2=nr(),y2=Di()});var Cf=g((JPe,b2)=>{var Ece=Di(),Cce=(r,e,t)=>{try{e=new Ece(e,t)}catch(i){return!1}return e.test(r)};b2.exports=Cce});var x2=g((YPe,w2)=>{var _ce=Di(),Pce=(r,e)=>new _ce(r,e).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));w2.exports=Pce});var S2=g((XPe,D2)=>{var Tce=nr(),Rce=Di(),kce=(r,e,t)=>{let i=null,n=null,o=null;try{o=new Rce(e,t)}catch(s){return null}return r.forEach(s=>{o.test(s)&&(!i||n.compare(s)===-1)&&(i=s,n=new Tce(i,t))}),i};D2.exports=kce});var C2=g((ZPe,E2)=>{var Ice=nr(),Fce=Di(),Ace=(r,e,t)=>{let i=null,n=null,o=null;try{o=new Fce(e,t)}catch(s){return null}return r.forEach(s=>{o.test(s)&&(!i||n.compare(s)===1)&&(i=s,n=new Ice(i,t))}),i};E2.exports=Ace});var P2=g((QPe,_2)=>{var jx=nr(),Oce=Di(),Lce=xf(),Mce=(r,e)=>{r=new Oce(r,e);let t=new jx("0.0.0");if(r.test(t)||(t=new jx("0.0.0-0"),r.test(t)))return t;t=null;for(let i=0;i{let s=new jx(o.semver.version);switch(o.operator){case">":s.prerelease.length===0?s.patch++:s.prerelease.push(0),s.raw=s.format();case"":case">=":(!t||Lce(t,s))&&(t=s);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}});return t&&r.test(t)?t:null};_2.exports=Mce});var R2=g((eTe,T2)=>{var Nce=Di(),qce=(r,e)=>{try{return new Nce(r,e).range||"*"}catch(t){return null}};T2.exports=qce});var Dm=g((tTe,k2)=>{var $ce=nr(),I2=Df(),{ANY:Bce}=I2,jce=Di(),Uce=Cf(),F2=xf(),A2=vm(),Wce=bm(),Hce=ym(),zce=(r,e,t,i)=>{r=new $ce(r,i),e=new jce(e,i);let n,o,s,a,l;switch(t){case">":n=F2,o=Wce,s=A2,a=">",l=">=";break;case"<":n=A2,o=Hce,s=F2,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Uce(r,e,i))return!1;for(let u=0;u{d.semver===Bce&&(d=new I2(">=0.0.0")),f=f||d,p=p||d,n(d.semver,f.semver,i)?f=d:s(d.semver,p.semver,i)&&(p=d)}),f.operator===a||f.operator===l||(!p.operator||p.operator===a)&&o(r,p.semver))return!1;if(p.operator===l&&s(r,p.semver))return!1}return!0};k2.exports=zce});var L2=g((rTe,O2)=>{var Gce=Dm(),Vce=(r,e,t)=>Gce(r,e,">",t);O2.exports=Vce});var N2=g((iTe,M2)=>{var Kce=Dm(),Jce=(r,e,t)=>Kce(r,e,"<",t);M2.exports=Jce});var B2=g((nTe,q2)=>{var $2=Di(),Yce=(r,e,t)=>(r=new $2(r,t),e=new $2(e,t),r.intersects(e));q2.exports=Yce});var U2=g((oTe,j2)=>{var Xce=Cf(),Zce=xi();j2.exports=(r,e,t)=>{let i=[],n=null,o=null,s=r.sort((c,f)=>Zce(c,f,t));for(let c of s)Xce(c,e,t)?(o=c,n||(n=c)):(o&&i.push([n,o]),o=null,n=null);n&&i.push([n,null]);let a=[];for(let[c,f]of i)c===f?a.push(c):!f&&c===s[0]?a.push("*"):f?c===s[0]?a.push(`<=${f}`):a.push(`${c} - ${f}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length{var H2=Di(),{ANY:z2}=Df(),_f=Cf(),Ux=xi(),efe=(r,e,t)=>{r=new H2(r,t),e=new H2(e,t);let i=!1;e:for(let n of r.set){for(let o of e.set){let s=Qce(n,o,t);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},Qce=(r,e,t)=>{if(r.length===1&&r[0].semver===z2)return e.length===1&&e[0].semver===z2;let i=new Set,n,o;for(let f of r)f.operator===">"||f.operator===">="?n=G2(n,f,t):f.operator==="<"||f.operator==="<="?o=V2(o,f,t):i.add(f.semver);if(i.size>1)return null;let s;if(n&&o){if(s=Ux(n.semver,o.semver,t),s>0)return null;if(s===0&&(n.operator!==">="||o.operator!=="<="))return null}for(let f of i){if(n&&!_f(f,String(n),t)||o&&!_f(f,String(o),t))return null;for(let p of e)if(!_f(f,String(p),t))return!1;return!0}let a,l,u,c;for(let f of e){if(c=c||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",n){if(f.operator===">"||f.operator===">="){if(a=G2(n,f,t),a===f)return!1}else if(n.operator===">="&&!_f(n.semver,String(f),t))return!1}if(o){if(f.operator==="<"||f.operator==="<="){if(l=V2(o,f,t),l===f)return!1}else if(o.operator==="<="&&!_f(o.semver,String(f),t))return!1}if(!f.operator&&(o||n)&&s!==0)return!1}return!(n&&u&&!o&&s!==0||o&&c&&!n&&s!==0)},G2=(r,e,t)=>{if(!r)return e;let i=Ux(r.semver,e.semver,t);return i>0?r:i<0||e.operator===">"&&r.operator===">="?e:r},V2=(r,e,t)=>{if(!r)return e;let i=Ux(r.semver,e.semver,t);return i<0?r:i>0||e.operator==="<"&&r.operator==="<="?e:r};W2.exports=efe});var Pf=g((aTe,J2)=>{var Wx=zs();J2.exports={re:Wx.re,src:Wx.src,tokens:Wx.t,SEMVER_SPEC_VERSION:yf().SEMVER_SPEC_VERSION,SemVer:nr(),compareIdentifiers:pm().compareIdentifiers,rcompareIdentifiers:pm().rcompareIdentifiers,parse:Gs(),valid:Rq(),clean:Iq(),inc:Aq(),diff:$q(),major:jq(),minor:Wq(),patch:zq(),prerelease:Vq(),compare:xi(),rcompare:Jq(),compareLoose:Xq(),compareBuild:gm(),sort:t2(),rsort:i2(),gt:xf(),lt:vm(),eq:mm(),neq:Mx(),gte:ym(),lte:bm(),cmp:Nx(),coerce:f2(),Comparator:Df(),Range:Di(),satisfies:Cf(),toComparators:x2(),maxSatisfying:S2(),minSatisfying:C2(),minVersion:P2(),validRange:R2(),outside:Dm(),gtr:L2(),ltr:N2(),intersects:B2(),simplifyRange:U2(),subset:K2()}});var kl=g((lTe,Hx)=>{function Y2(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}function tfe(r){Hx.exports.defaults=r}Hx.exports={defaults:Y2(),getDefaults:Y2,changeDefaults:tfe}});var Vs=g((uTe,X2)=>{var rfe=/[&<>"']/,ife=/[&<>"']/g,nfe=/[<>"']|&(?!#?\w+;)/,ofe=/[<>"']|&(?!#?\w+;)/g,sfe={"&":"&","<":"<",">":">",'"':""","'":"'"},Z2=r=>sfe[r];function afe(r,e){if(e){if(rfe.test(r))return r.replace(ife,Z2)}else if(nfe.test(r))return r.replace(ofe,Z2);return r}var lfe=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Q2(r){return r.replace(lfe,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}var ufe=/(^|[^\[])\^/g;function cfe(r,e){r=r.source||r,e=e||"";let t={replace:(i,n)=>(n=n.source||n,n=n.replace(ufe,"$1"),r=r.replace(i,n),t),getRegex:()=>new RegExp(r,e)};return t}var ffe=/[^\w:]/g,pfe=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function dfe(r,e,t){if(r){let i;try{i=decodeURIComponent(Q2(t)).replace(ffe,"").toLowerCase()}catch(n){return null}if(i.indexOf("javascript:")===0||i.indexOf("vbscript:")===0||i.indexOf("data:")===0)return null}e&&!pfe.test(t)&&(t=e$(e,t));try{t=encodeURI(t).replace(/%25/g,"%")}catch(i){return null}return t}var Sm={},hfe=/^[^:]+:\/*[^/]*$/,mfe=/^([^:]+:)[\s\S]*$/,gfe=/^([^:]+:\/*[^/]*)[\s\S]*$/;function e$(r,e){Sm[" "+r]||(hfe.test(r)?Sm[" "+r]=r+"/":Sm[" "+r]=t$(r,"/",!0)),r=Sm[" "+r];let t=r.indexOf(":")===-1;return e.substring(0,2)==="//"?t?e:r.replace(mfe,"$1")+e:e.charAt(0)==="/"?t?e:r.replace(gfe,"$1")+e:r+e}var vfe={exec:function(){}};function yfe(r){let e=1,t,i;for(;e{let l=!1,u=s;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),i=t.split(/ \|/),n=0;if(i.length>e)i.splice(e);else for(;i.length1;)e&1&&(t+=r),e>>=1,r+=r;return t+r}X2.exports={escape:afe,unescape:Q2,edit:cfe,cleanUrl:dfe,resolveUrl:e$,noopTest:vfe,merge:yfe,splitCells:bfe,rtrim:t$,findClosingBracket:wfe,checkSanitizeDeprecation:xfe,repeatString:Dfe}});var zx=g((fTe,r$)=>{var{defaults:Sfe}=kl(),{rtrim:Efe,splitCells:Em,escape:Si,findClosingBracket:Cfe}=Vs();function i$(r,e,t){let i=e.href,n=e.title?Si(e.title):null,o=r[1].replace(/\\([\[\]])/g,"$1");return r[0].charAt(0)!=="!"?{type:"link",raw:t,href:i,title:n,text:o}:{type:"image",raw:t,href:i,title:n,text:Si(o)}}function _fe(r,e){let t=r.match(/^(\s+)(?:```)/);if(t===null)return e;let i=t[1];return e.split(` +`).map(n=>{let o=n.match(/^\s+/);if(o===null)return n;let[s]=o;return s.length>=i.length?n.slice(i.length):n}).join(` +`)}r$.exports=class{constructor(e){this.options=e||Sfe}space(e){let t=this.rules.block.newline.exec(e);if(t)return t[0].length>1?{type:"space",raw:t[0]}:{raw:` +`}}code(e,t){let i=this.rules.block.code.exec(e);if(i){let n=t[t.length-1];if(n&&n.type==="paragraph")return{raw:i[0],text:i[0].trimRight()};let o=i[0].replace(/^ {4}/gm,"");return{type:"code",raw:i[0],codeBlockStyle:"indented",text:this.options.pedantic?o:Efe(o,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],n=_fe(i,t[3]||"");return{type:"code",raw:i,lang:t[2]?t[2].trim():t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[1].length,text:t[2]}}nptable(e){let t=this.rules.block.nptable.exec(e);if(t){let i={type:"table",header:Em(t[1].replace(/^ *| *\| *$/g,"")),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:t[3]?t[3].replace(/\n$/,"").split(` +`):[],raw:t[0]};if(i.header.length===i.align.length){let n=i.align.length,o;for(o=0;o ?/gm,"");return{type:"blockquote",raw:t[0],text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[0],n=t[2],o=n.length>1,s={type:"list",raw:i,ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]},a=t[0].match(this.rules.block.item),l=!1,u,c,f,p,d,h,m,y,v=a.length;f=this.rules.block.listItemStart.exec(a[0]);for(let x=0;xf[0].length||p[1].length>3){a.splice(x,2,a[x]+` +`+a[x+1]),x--,v--;continue}else(!this.options.pedantic||this.options.smartLists?p[2][p[2].length-1]!==n[n.length-1]:o===(p[2].length===1))&&(d=a.slice(x+1).join(` +`),s.raw=s.raw.substring(0,s.raw.length-d.length),x=v-1);f=p}c=u.length,u=u.replace(/^ *([*+-]|\d+[.)]) ?/,""),~u.indexOf(` + `)&&(c-=u.length,u=this.options.pedantic?u.replace(/^ {1,4}/gm,""):u.replace(new RegExp("^ {1,"+c+"}","gm"),"")),h=l||/\n\n(?!\s*$)/.test(u),x!==v-1&&(l=u.charAt(u.length-1)===` +`,h||(h=l)),h&&(s.loose=!0),this.options.gfm&&(m=/^\[[ xX]\] /.test(u),y=void 0,m&&(y=u[1]!==" ",u=u.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:m,checked:y,loose:h,text:u})}return s}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:this.options.sanitize?"paragraph":"html",raw:t[0],pre:!this.options.sanitizer&&(t[1]==="pre"||t[1]==="script"||t[1]==="style"),text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):Si(t[0]):t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t)return t[3]&&(t[3]=t[3].substring(1,t[3].length-1)),{tag:t[1].toLowerCase().replace(/\s+/g," "),raw:t[0],href:t[2],title:t[3]}}table(e){let t=this.rules.block.table.exec(e);if(t){let i={type:"table",header:Em(t[1].replace(/^ *| *\| *$/g,"")),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:t[3]?t[3].replace(/\n$/,"").split(` +`):[]};if(i.header.length===i.align.length){i.raw=t[0];let n=i.align.length,o;for(o=0;o/i.test(n[0])&&(t=!1),!i&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?i=!0:i&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(i=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:t,inRawBlock:i,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):Si(n[0]):n[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=Cfe(t[2],"()");if(i>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,l).trim(),t[3]=""}let n=t[2],o="";if(this.options.pedantic){let a=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);a?(n=a[1],o=a[3]):o=""}else o=t[3]?t[3].slice(1,-1):"";return n=n.trim().replace(/^<([\s\S]*)>$/,"$1"),i$(t,{href:n&&n.replace(this.rules.inline._escapes,"$1"),title:o&&o.replace(this.rules.inline._escapes,"$1")},t[0])}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let n=(i[2]||i[1]).replace(/\s+/g," ");if(n=t[n.toLowerCase()],!n||!n.href){let s=i[0].charAt(0);return{type:"text",raw:s,text:s}}return i$(i,n,i[0])}}strong(e,t,i=""){let n=this.rules.inline.strong.start.exec(e);if(n&&(!n[1]||n[1]&&(i===""||this.rules.inline.punctuation.exec(i)))){t=t.slice(-1*e.length);let o=n[0]==="**"?this.rules.inline.strong.endAst:this.rules.inline.strong.endUnd;o.lastIndex=0;let s;for(;(n=o.exec(t))!=null;)if(s=this.rules.inline.strong.middle.exec(t.slice(0,n.index+3)),s)return{type:"strong",raw:e.slice(0,s[0].length),text:e.slice(2,s[0].length-2)}}}em(e,t,i=""){let n=this.rules.inline.em.start.exec(e);if(n&&(!n[1]||n[1]&&(i===""||this.rules.inline.punctuation.exec(i)))){t=t.slice(-1*e.length);let o=n[0]==="*"?this.rules.inline.em.endAst:this.rules.inline.em.endUnd;o.lastIndex=0;let s;for(;(n=o.exec(t))!=null;)if(s=this.rules.inline.em.middle.exec(t.slice(0,n.index+2)),s)return{type:"em",raw:e.slice(0,s[0].length),text:e.slice(1,s[0].length-1)}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(/\n/g," "),n=/[^ ]/.test(i),o=i.startsWith(" ")&&i.endsWith(" ");return n&&o&&(i=i.substring(1,i.length-1)),i=Si(i,!0),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2]}}autolink(e,t){let i=this.rules.inline.autolink.exec(e);if(i){let n,o;return i[2]==="@"?(n=Si(this.options.mangle?t(i[1]):i[1]),o="mailto:"+n):(n=Si(i[1]),o=n),{type:"link",raw:i[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e,t){let i;if(i=this.rules.inline.url.exec(e)){let n,o;if(i[2]==="@")n=Si(this.options.mangle?t(i[0]):i[0]),o="mailto:"+n;else{let s;do s=i[0],i[0]=this.rules.inline._backpedal.exec(i[0])[0];while(s!==i[0]);n=Si(i[0]),i[1]==="www."?o="http://"+n:o=n}return{type:"link",raw:i[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e,t,i){let n=this.rules.inline.text.exec(e);if(n){let o;return t?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):Si(n[0]):n[0]:o=Si(this.options.smartypants?i(n[0]):n[0]),{type:"text",raw:n[0],text:o}}}}});var o$=g((pTe,n$)=>{var{noopTest:Tf,edit:Te,merge:Ks}=Vs(),se={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,nptable:Tf,table:Tf,lheading:/^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/,text:/^[^\n]+/};se._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;se._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;se.def=Te(se.def).replace("label",se._label).replace("title",se._title).getRegex();se.bullet=/(?:[*+-]|\d{1,9}[.)])/;se.item=/^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/;se.item=Te(se.item,"gm").replace(/bull/g,se.bullet).getRegex();se.listItemStart=Te(/^( *)(bull)/).replace("bull",se.bullet).getRegex();se.list=Te(se.list).replace(/bull/g,se.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+se.def.source+")").getRegex();se._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";se._comment=/|$)/;se.html=Te(se.html,"i").replace("comment",se._comment).replace("tag",se._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();se.paragraph=Te(se._paragraph).replace("hr",se.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",se._tag).getRegex();se.blockquote=Te(se.blockquote).replace("paragraph",se.paragraph).getRegex();se.normal=Ks({},se);se.gfm=Ks({},se.normal,{nptable:"^ *([^|\\n ].*\\|.*)\\n {0,3}([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)",table:"^ *\\|(.+)\\n {0,3}\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"});se.gfm.nptable=Te(se.gfm.nptable).replace("hr",se.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",se._tag).getRegex();se.gfm.table=Te(se.gfm.table).replace("hr",se.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",se._tag).getRegex();se.pedantic=Ks({},se.normal,{html:Te(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",se._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,fences:Tf,paragraph:Te(se.normal._paragraph).replace("hr",se.hr).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",se.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});var H={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:Tf,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",strong:{start:/^(?:(\*\*(?=[*punctuation]))|\*\*)(?![\s])|__/,middle:/^\*\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?)__$/,endAst:/[^punctuation\s]\*\*(?!\*)|[punctuation]\*\*(?!\*)(?:(?=[punctuation_\s]|$))/,endUnd:/[^\s]__(?!_)(?:(?=[punctuation*\s])|$)/},em:{start:/^(?:(\*(?=[punctuation]))|\*)(?![*\s])|_/,middle:/^\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?_$/,endAst:/[^punctuation\s]\*(?!\*)|[punctuation]\*(?!\*)(?:(?=[punctuation_\s]|$))/,endUnd:/[^\s]_(?!_)(?:(?=[punctuation*\s])|$)/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:Tf,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~";H.punctuation=Te(H.punctuation).replace(/punctuation/g,H._punctuation).getRegex();H._blockSkip="\\[[^\\]]*?\\]\\([^\\)]*?\\)|`[^`]*?`|<[^>]*?>";H._overlapSkip="__[^_]*?__|\\*\\*\\[^\\*\\]*?\\*\\*";H._comment=Te(se._comment).replace("(?:-->|$)","-->").getRegex();H.em.start=Te(H.em.start).replace(/punctuation/g,H._punctuation).getRegex();H.em.middle=Te(H.em.middle).replace(/punctuation/g,H._punctuation).replace(/overlapSkip/g,H._overlapSkip).getRegex();H.em.endAst=Te(H.em.endAst,"g").replace(/punctuation/g,H._punctuation).getRegex();H.em.endUnd=Te(H.em.endUnd,"g").replace(/punctuation/g,H._punctuation).getRegex();H.strong.start=Te(H.strong.start).replace(/punctuation/g,H._punctuation).getRegex();H.strong.middle=Te(H.strong.middle).replace(/punctuation/g,H._punctuation).replace(/overlapSkip/g,H._overlapSkip).getRegex();H.strong.endAst=Te(H.strong.endAst,"g").replace(/punctuation/g,H._punctuation).getRegex();H.strong.endUnd=Te(H.strong.endUnd,"g").replace(/punctuation/g,H._punctuation).getRegex();H.blockSkip=Te(H._blockSkip,"g").getRegex();H.overlapSkip=Te(H._overlapSkip,"g").getRegex();H._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;H._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;H._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;H.autolink=Te(H.autolink).replace("scheme",H._scheme).replace("email",H._email).getRegex();H._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;H.tag=Te(H.tag).replace("comment",H._comment).replace("attribute",H._attribute).getRegex();H._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;H._href=/<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/;H._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;H.link=Te(H.link).replace("label",H._label).replace("href",H._href).replace("title",H._title).getRegex();H.reflink=Te(H.reflink).replace("label",H._label).getRegex();H.reflinkSearch=Te(H.reflinkSearch,"g").replace("reflink",H.reflink).replace("nolink",H.nolink).getRegex();H.normal=Ks({},H);H.pedantic=Ks({},H.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",H._label).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",H._label).getRegex()});H.gfm=Ks({},H.normal,{escape:Te(H.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\{var Pfe=zx(),{defaults:Tfe}=kl(),{block:Cm,inline:Rf}=o$(),{repeatString:a$}=Vs();function Rfe(r){return r.replace(/---/g,"\u2014").replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201C").replace(/"/g,"\u201D").replace(/\.{3}/g,"\u2026")}function l$(r){let e="",t,i,n=r.length;for(t=0;t.5&&(i="x"+i.toString(16)),e+="&#"+i+";";return e}s$.exports=class Gx{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Tfe,this.options.tokenizer=this.options.tokenizer||new Pfe,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options;let t={block:Cm.normal,inline:Rf.normal};this.options.pedantic?(t.block=Cm.pedantic,t.inline=Rf.pedantic):this.options.gfm&&(t.block=Cm.gfm,this.options.breaks?t.inline=Rf.breaks:t.inline=Rf.gfm),this.tokenizer.rules=t}static get rules(){return{block:Cm,inline:Rf}}static lex(e,t){return new Gx(t).lex(e)}static lexInline(e,t){return new Gx(t).inlineTokens(e)}lex(e){return e=e.replace(/\r\n|\r/g,` +`).replace(/\t/g," "),this.blockTokens(e,this.tokens,!0),this.inline(this.tokens),this.tokens}blockTokens(e,t=[],i=!0){e=e.replace(/^ +$/gm,"");let n,o,s,a;for(;e;){if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length),n.type&&t.push(n);continue}if(n=this.tokenizer.code(e,t)){e=e.substring(n.raw.length),n.type?t.push(n):(a=t[t.length-1],a.raw+=` +`+n.raw,a.text+=` +`+n.text);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.nptable(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),n.tokens=this.blockTokens(n.text,[],i),t.push(n);continue}if(n=this.tokenizer.list(e)){for(e=e.substring(n.raw.length),s=n.items.length,o=0;o0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)c.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,a.index)+"["+a$("a",a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,a.index)+"["+a$("a",a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;e;){if(l||(u=""),l=!1,o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e,i,n)){e=e.substring(o.raw.length),i=o.inLink,n=o.inRawBlock,t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),o.type==="link"&&(o.tokens=this.inlineTokens(o.text,[],!0,n)),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length),o.type==="link"&&(o.tokens=this.inlineTokens(o.text,[],!0,n)),t.push(o);continue}if(o=this.tokenizer.strong(e,s,u)){e=e.substring(o.raw.length),o.tokens=this.inlineTokens(o.text,[],i,n),t.push(o);continue}if(o=this.tokenizer.em(e,s,u)){e=e.substring(o.raw.length),o.tokens=this.inlineTokens(o.text,[],i,n),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),o.tokens=this.inlineTokens(o.text,[],i,n),t.push(o);continue}if(o=this.tokenizer.autolink(e,l$)){e=e.substring(o.raw.length),t.push(o);continue}if(!i&&(o=this.tokenizer.url(e,l$))){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.inlineText(e,n,Rfe)){e=e.substring(o.raw.length),u=o.raw.slice(-1),l=!0,t.push(o);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}}});var Vx=g((mTe,c$)=>{var{defaults:kfe}=kl(),{cleanUrl:f$,escape:_m}=Vs();c$.exports=class{constructor(e){this.options=e||kfe}code(e,t,i){let n=(t||"").match(/\S*/)[0];if(this.options.highlight){let o=this.options.highlight(e,n);o!=null&&o!==e&&(i=!0,e=o)}return n?'
'+(i?e:_m(e,!0))+`
+`:"
"+(i?e:_m(e,!0))+`
+`}blockquote(e){return`
+`+e+`
+`}html(e){return e}heading(e,t,i,n){return this.options.headerIds?"'+e+" +`:""+e+" +`}hr(){return this.options.xhtml?`
+`:`
+`}list(e,t,i){let n=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+n+o+`> +`+e+" +`}listitem(e){return"
  • "+e+`
  • +`}checkbox(e){return" "}paragraph(e){return"

    "+e+`

    +`}table(e,t){return t&&(t=""+t+""),` + +`+e+` +`+t+`
    +`}tablerow(e){return` +`+e+` +`}tablecell(e,t){let i=t.header?"th":"td";return(t.align?"<"+i+' align="'+t.align+'">':"<"+i+">")+e+" +`}strong(e){return""+e+""}em(e){return""+e+""}codespan(e){return""+e+""}br(){return this.options.xhtml?"
    ":"
    "}del(e){return""+e+""}link(e,t,i){if(e=f$(this.options.sanitize,this.options.baseUrl,e),e===null)return i;let n='",n}image(e,t,i){if(e=f$(this.options.sanitize,this.options.baseUrl,e),e===null)return i;let n=''+i+'":">",n}text(e){return e}}});var Kx=g((vTe,p$)=>{p$.exports=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,i){return""+i}image(e,t,i){return""+i}br(){return""}}});var Jx=g((bTe,d$)=>{d$.exports=class{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let i=e,n=0;if(this.seen.hasOwnProperty(i)){n=this.seen[e];do n++,i=e+"-"+n;while(this.seen.hasOwnProperty(i))}return t||(this.seen[e]=n,this.seen[i]=0),i}slug(e,t={}){let i=this.serialize(e);return this.getNextSafeSlug(i,t.dryrun)}}});var m$=g((wTe,h$)=>{var Ife=Vx(),Ffe=Kx(),Afe=Jx(),{defaults:Ofe}=kl(),{unescape:Lfe}=Vs();h$.exports=class Yx{constructor(e){this.options=e||Ofe,this.options.renderer=this.options.renderer||new Ife,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ffe,this.slugger=new Afe}static parse(e,t){return new Yx(t).parse(e)}static parseInline(e,t){return new Yx(t).parseInline(e)}parse(e,t=!0){let i="",n,o,s,a,l,u,c,f,p,d,h,m,y,v,x,w,E,P,k=e.length;for(n=0;n0&&x.tokens[0].type==="text"?(x.tokens[0].text=P+" "+x.tokens[0].text,x.tokens[0].tokens&&x.tokens[0].tokens.length>0&&x.tokens[0].tokens[0].type==="text"&&(x.tokens[0].tokens[0].text=P+" "+x.tokens[0].tokens[0].text)):x.tokens.unshift({type:"text",text:P}):v+=P),v+=this.parse(x.tokens,y),p+=this.renderer.listitem(v,E,w);i+=this.renderer.list(p,h,m);continue}case"html":{i+=this.renderer.html(d.text);continue}case"paragraph":{i+=this.renderer.paragraph(this.parseInline(d.tokens));continue}case"text":{for(p=d.tokens?this.parseInline(d.tokens):d.text;n+1{var kf=u$(),If=m$(),v$=zx(),y$=Vx(),Mfe=Kx(),Nfe=Jx(),{merge:Pm,checkSanitizeDeprecation:b$,escape:w$}=Vs(),{getDefaults:qfe,changeDefaults:$fe,defaults:Bfe}=kl();function Re(r,e,t){if(typeof r=="undefined"||r===null)throw new Error("marked(): input parameter is undefined or null");if(typeof r!="string")throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(r)+", string expected");if(typeof e=="function"&&(t=e,e=null),e=Pm({},Re.defaults,e||{}),b$(e),t){let i=e.highlight,n;try{n=kf.lex(r,e)}catch(a){return t(a)}let o=function(a){let l;if(!a)try{l=If.parse(n,e)}catch(u){a=u}return e.highlight=i,a?t(a):t(null,l)};if(!i||i.length<3||(delete e.highlight,!n.length))return o();let s=0;Re.walkTokens(n,function(a){a.type==="code"&&(s++,setTimeout(()=>{i(a.text,a.lang,function(l,u){if(l)return o(l);u!=null&&u!==a.text&&(a.text=u,a.escaped=!0),s--,s===0&&o()})},0))}),s===0&&o();return}try{let i=kf.lex(r,e);return e.walkTokens&&Re.walkTokens(i,e.walkTokens),If.parse(i,e)}catch(i){if(i.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+w$(i.message+"",!0)+"
    ";throw i}}Re.options=Re.setOptions=function(r){return Pm(Re.defaults,r),$fe(Re.defaults),Re};Re.getDefaults=qfe;Re.defaults=Bfe;Re.use=function(r){let e=Pm({},r);if(r.renderer){let t=Re.defaults.renderer||new y$;for(let i in r.renderer){let n=t[i];t[i]=(...o)=>{let s=r.renderer[i].apply(t,o);return s===!1&&(s=n.apply(t,o)),s}}e.renderer=t}if(r.tokenizer){let t=Re.defaults.tokenizer||new v$;for(let i in r.tokenizer){let n=t[i];t[i]=(...o)=>{let s=r.tokenizer[i].apply(t,o);return s===!1&&(s=n.apply(t,o)),s}}e.tokenizer=t}if(r.walkTokens){let t=Re.defaults.walkTokens;e.walkTokens=i=>{r.walkTokens(i),t&&t(i)}}Re.setOptions(e)};Re.walkTokens=function(r,e){for(let t of r)switch(e(t),t.type){case"table":{for(let i of t.tokens.header)Re.walkTokens(i,e);for(let i of t.tokens.cells)for(let n of i)Re.walkTokens(n,e);break}case"list":{Re.walkTokens(t.items,e);break}default:t.tokens&&Re.walkTokens(t.tokens,e)}};Re.parseInline=function(r,e){if(typeof r=="undefined"||r===null)throw new Error("marked.parseInline(): input parameter is undefined or null");if(typeof r!="string")throw new Error("marked.parseInline(): input parameter is of type "+Object.prototype.toString.call(r)+", string expected");e=Pm({},Re.defaults,e||{}),b$(e);try{let t=kf.lexInline(r,e);return e.walkTokens&&Re.walkTokens(t,e.walkTokens),If.parseInline(t,e)}catch(t){if(t.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+w$(t.message+"",!0)+"
    ";throw t}};Re.Parser=If;Re.parser=If.parse;Re.Renderer=y$;Re.TextRenderer=Mfe;Re.Lexer=kf;Re.lexer=kf.lex;Re.Tokenizer=v$;Re.Slugger=Nfe;Re.parse=Re;g$.exports=Re});var S$=g((DTe,D$)=>{"use strict";var jfe=/[|\\{}()[\]^$+*?.]/g;D$.exports=function(r){if(typeof r!="string")throw new TypeError("Expected a string");return r.replace(jfe,"\\$&")}});var C$=g((STe,E$)=>{"use strict";E$.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Zx=g((ETe,_$)=>{var Js=C$(),P$={};for(var Xx in Js)Js.hasOwnProperty(Xx)&&(P$[Js[Xx]]=Xx);var ee=_$.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var kr in ee)if(ee.hasOwnProperty(kr)){if(!("channels"in ee[kr]))throw new Error("missing channels property: "+kr);if(!("labels"in ee[kr]))throw new Error("missing channel labels property: "+kr);if(ee[kr].labels.length!==ee[kr].channels)throw new Error("channel and label counts mismatch: "+kr);T$=ee[kr].channels,R$=ee[kr].labels,delete ee[kr].channels,delete ee[kr].labels,Object.defineProperty(ee[kr],"channels",{value:T$}),Object.defineProperty(ee[kr],"labels",{value:R$})}var T$,R$;ee.rgb.hsl=function(r){var e=r[0]/255,t=r[1]/255,i=r[2]/255,n=Math.min(e,t,i),o=Math.max(e,t,i),s=o-n,a,l,u;return o===n?a=0:e===o?a=(t-i)/s:t===o?a=2+(i-e)/s:i===o&&(a=4+(e-t)/s),a=Math.min(a*60,360),a<0&&(a+=360),u=(n+o)/2,o===n?l=0:u<=.5?l=s/(o+n):l=s/(2-o-n),[a,l*100,u*100]};ee.rgb.hsv=function(r){var e,t,i,n,o,s=r[0]/255,a=r[1]/255,l=r[2]/255,u=Math.max(s,a,l),c=u-Math.min(s,a,l),f=function(p){return(u-p)/6/c+1/2};return c===0?n=o=0:(o=c/u,e=f(s),t=f(a),i=f(l),s===u?n=i-t:a===u?n=1/3+e-i:l===u&&(n=2/3+t-e),n<0?n+=1:n>1&&(n-=1)),[n*360,o*100,u*100]};ee.rgb.hwb=function(r){var e=r[0],t=r[1],i=r[2],n=ee.rgb.hsl(r)[0],o=1/255*Math.min(e,Math.min(t,i));return i=1-1/255*Math.max(e,Math.max(t,i)),[n,o*100,i*100]};ee.rgb.cmyk=function(r){var e=r[0]/255,t=r[1]/255,i=r[2]/255,n,o,s,a;return a=Math.min(1-e,1-t,1-i),n=(1-e-a)/(1-a)||0,o=(1-t-a)/(1-a)||0,s=(1-i-a)/(1-a)||0,[n*100,o*100,s*100,a*100]};function Ufe(r,e){return Math.pow(r[0]-e[0],2)+Math.pow(r[1]-e[1],2)+Math.pow(r[2]-e[2],2)}ee.rgb.keyword=function(r){var e=P$[r];if(e)return e;var t=Infinity,i;for(var n in Js)if(Js.hasOwnProperty(n)){var o=Js[n],s=Ufe(r,o);s.04045?Math.pow((e+.055)/1.055,2.4):e/12.92,t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92,i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92;var n=e*.4124+t*.3576+i*.1805,o=e*.2126+t*.7152+i*.0722,s=e*.0193+t*.1192+i*.9505;return[n*100,o*100,s*100]};ee.rgb.lab=function(r){var e=ee.rgb.xyz(r),t=e[0],i=e[1],n=e[2],o,s,a;return t/=95.047,i/=100,n/=108.883,t=t>.008856?Math.pow(t,1/3):7.787*t+16/116,i=i>.008856?Math.pow(i,1/3):7.787*i+16/116,n=n>.008856?Math.pow(n,1/3):7.787*n+16/116,o=116*i-16,s=500*(t-i),a=200*(i-n),[o,s,a]};ee.hsl.rgb=function(r){var e=r[0]/360,t=r[1]/100,i=r[2]/100,n,o,s,a,l;if(t===0)return l=i*255,[l,l,l];i<.5?o=i*(1+t):o=i+t-i*t,n=2*i-o,a=[0,0,0];for(var u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?l=n+(o-n)*6*s:2*s<1?l=o:3*s<2?l=n+(o-n)*(2/3-s)*6:l=n,a[u]=l*255;return a};ee.hsl.hsv=function(r){var e=r[0],t=r[1]/100,i=r[2]/100,n=t,o=Math.max(i,.01),s,a;return i*=2,t*=i<=1?i:2-i,n*=o<=1?o:2-o,a=(i+t)/2,s=i===0?2*n/(o+n):2*t/(i+t),[e,s*100,a*100]};ee.hsv.rgb=function(r){var e=r[0]/60,t=r[1]/100,i=r[2]/100,n=Math.floor(e)%6,o=e-Math.floor(e),s=255*i*(1-t),a=255*i*(1-t*o),l=255*i*(1-t*(1-o));switch(i*=255,n){case 0:return[i,l,s];case 1:return[a,i,s];case 2:return[s,i,l];case 3:return[s,a,i];case 4:return[l,s,i];case 5:return[i,s,a]}};ee.hsv.hsl=function(r){var e=r[0],t=r[1]/100,i=r[2]/100,n=Math.max(i,.01),o,s,a;return a=(2-t)*i,o=(2-t)*n,s=t*n,s/=o<=1?o:2-o,s=s||0,a/=2,[e,s*100,a*100]};ee.hwb.rgb=function(r){var e=r[0]/360,t=r[1]/100,i=r[2]/100,n=t+i,o,s,a,l;n>1&&(t/=n,i/=n),o=Math.floor(6*e),s=1-i,a=6*e-o,(o&1)!=0&&(a=1-a),l=t+a*(s-t);var u,c,f;switch(o){default:case 6:case 0:u=s,c=l,f=t;break;case 1:u=l,c=s,f=t;break;case 2:u=t,c=s,f=l;break;case 3:u=t,c=l,f=s;break;case 4:u=l,c=t,f=s;break;case 5:u=s,c=t,f=l;break}return[u*255,c*255,f*255]};ee.cmyk.rgb=function(r){var e=r[0]/100,t=r[1]/100,i=r[2]/100,n=r[3]/100,o,s,a;return o=1-Math.min(1,e*(1-n)+n),s=1-Math.min(1,t*(1-n)+n),a=1-Math.min(1,i*(1-n)+n),[o*255,s*255,a*255]};ee.xyz.rgb=function(r){var e=r[0]/100,t=r[1]/100,i=r[2]/100,n,o,s;return n=e*3.2406+t*-1.5372+i*-.4986,o=e*-.9689+t*1.8758+i*.0415,s=e*.0557+t*-.204+i*1.057,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:n*12.92,o=o>.0031308?1.055*Math.pow(o,1/2.4)-.055:o*12.92,s=s>.0031308?1.055*Math.pow(s,1/2.4)-.055:s*12.92,n=Math.min(Math.max(0,n),1),o=Math.min(Math.max(0,o),1),s=Math.min(Math.max(0,s),1),[n*255,o*255,s*255]};ee.xyz.lab=function(r){var e=r[0],t=r[1],i=r[2],n,o,s;return e/=95.047,t/=100,i/=108.883,e=e>.008856?Math.pow(e,1/3):7.787*e+16/116,t=t>.008856?Math.pow(t,1/3):7.787*t+16/116,i=i>.008856?Math.pow(i,1/3):7.787*i+16/116,n=116*t-16,o=500*(e-t),s=200*(t-i),[n,o,s]};ee.lab.xyz=function(r){var e=r[0],t=r[1],i=r[2],n,o,s;o=(e+16)/116,n=t/500+o,s=o-i/200;var a=Math.pow(o,3),l=Math.pow(n,3),u=Math.pow(s,3);return o=a>.008856?a:(o-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,s=u>.008856?u:(s-16/116)/7.787,n*=95.047,o*=100,s*=108.883,[n,o,s]};ee.lab.lch=function(r){var e=r[0],t=r[1],i=r[2],n,o,s;return n=Math.atan2(i,t),o=n*360/2/Math.PI,o<0&&(o+=360),s=Math.sqrt(t*t+i*i),[e,s,o]};ee.lch.lab=function(r){var e=r[0],t=r[1],i=r[2],n,o,s;return s=i/360*2*Math.PI,n=t*Math.cos(s),o=t*Math.sin(s),[e,n,o]};ee.rgb.ansi16=function(r){var e=r[0],t=r[1],i=r[2],n=1 in arguments?arguments[1]:ee.rgb.hsv(r)[2];if(n=Math.round(n/50),n===0)return 30;var o=30+(Math.round(i/255)<<2|Math.round(t/255)<<1|Math.round(e/255));return n===2&&(o+=60),o};ee.hsv.ansi16=function(r){return ee.rgb.ansi16(ee.hsv.rgb(r),r[2])};ee.rgb.ansi256=function(r){var e=r[0],t=r[1],i=r[2];if(e===t&&t===i)return e<8?16:e>248?231:Math.round((e-8)/247*24)+232;var n=16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(i/255*5);return n};ee.ansi16.rgb=function(r){var e=r%10;if(e===0||e===7)return r>50&&(e+=3.5),e=e/10.5*255,[e,e,e];var t=(~~(r>50)+1)*.5,i=(e&1)*t*255,n=(e>>1&1)*t*255,o=(e>>2&1)*t*255;return[i,n,o]};ee.ansi256.rgb=function(r){if(r>=232){var e=(r-232)*10+8;return[e,e,e]}r-=16;var t,i=Math.floor(r/36)/5*255,n=Math.floor((t=r%36)/6)/5*255,o=t%6/5*255;return[i,n,o]};ee.rgb.hex=function(r){var e=((Math.round(r[0])&255)<<16)+((Math.round(r[1])&255)<<8)+(Math.round(r[2])&255),t=e.toString(16).toUpperCase();return"000000".substring(t.length)+t};ee.hex.rgb=function(r){var e=r.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];var t=e[0];e[0].length===3&&(t=t.split("").map(function(a){return a+a}).join(""));var i=parseInt(t,16),n=i>>16&255,o=i>>8&255,s=i&255;return[n,o,s]};ee.rgb.hcg=function(r){var e=r[0]/255,t=r[1]/255,i=r[2]/255,n=Math.max(Math.max(e,t),i),o=Math.min(Math.min(e,t),i),s=n-o,a,l;return s<1?a=o/(1-s):a=0,s<=0?l=0:n===e?l=(t-i)/s%6:n===t?l=2+(i-e)/s:l=4+(e-t)/s+4,l/=6,l%=1,[l*360,s*100,a*100]};ee.hsl.hcg=function(r){var e=r[1]/100,t=r[2]/100,i=1,n=0;return t<.5?i=2*e*t:i=2*e*(1-t),i<1&&(n=(t-.5*i)/(1-i)),[r[0],i*100,n*100]};ee.hsv.hcg=function(r){var e=r[1]/100,t=r[2]/100,i=e*t,n=0;return i<1&&(n=(t-i)/(1-i)),[r[0],i*100,n*100]};ee.hcg.rgb=function(r){var e=r[0]/360,t=r[1]/100,i=r[2]/100;if(t===0)return[i*255,i*255,i*255];var n=[0,0,0],o=e%1*6,s=o%1,a=1-s,l=0;switch(Math.floor(o)){case 0:n[0]=1,n[1]=s,n[2]=0;break;case 1:n[0]=a,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=s;break;case 3:n[0]=0,n[1]=a,n[2]=1;break;case 4:n[0]=s,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=a}return l=(1-t)*i,[(t*n[0]+l)*255,(t*n[1]+l)*255,(t*n[2]+l)*255]};ee.hcg.hsv=function(r){var e=r[1]/100,t=r[2]/100,i=e+t*(1-e),n=0;return i>0&&(n=e/i),[r[0],n*100,i*100]};ee.hcg.hsl=function(r){var e=r[1]/100,t=r[2]/100,i=t*(1-e)+.5*e,n=0;return i>0&&i<.5?n=e/(2*i):i>=.5&&i<1&&(n=e/(2*(1-i))),[r[0],n*100,i*100]};ee.hcg.hwb=function(r){var e=r[1]/100,t=r[2]/100,i=e+t*(1-e);return[r[0],(i-e)*100,(1-i)*100]};ee.hwb.hcg=function(r){var e=r[1]/100,t=r[2]/100,i=1-t,n=i-e,o=0;return n<1&&(o=(i-n)/(1-n)),[r[0],n*100,o*100]};ee.apple.rgb=function(r){return[r[0]/65535*255,r[1]/65535*255,r[2]/65535*255]};ee.rgb.apple=function(r){return[r[0]/255*65535,r[1]/255*65535,r[2]/255*65535]};ee.gray.rgb=function(r){return[r[0]/100*255,r[0]/100*255,r[0]/100*255]};ee.gray.hsl=ee.gray.hsv=function(r){return[0,0,r[0]]};ee.gray.hwb=function(r){return[0,100,r[0]]};ee.gray.cmyk=function(r){return[0,0,0,r[0]]};ee.gray.lab=function(r){return[r[0],0,0]};ee.gray.hex=function(r){var e=Math.round(r[0]/100*255)&255,t=(e<<16)+(e<<8)+e,i=t.toString(16).toUpperCase();return"000000".substring(i.length)+i};ee.rgb.gray=function(r){var e=(r[0]+r[1]+r[2])/3;return[e/255*100]}});var I$=g((CTe,k$)=>{var Tm=Zx();function Wfe(){for(var r={},e=Object.keys(Tm),t=e.length,i=0;i{var Qx=Zx(),Vfe=I$(),Il={},Kfe=Object.keys(Qx);function Jfe(r){var e=function(t){return t==null?t:(arguments.length>1&&(t=Array.prototype.slice.call(arguments)),r(t))};return"conversion"in r&&(e.conversion=r.conversion),e}function Yfe(r){var e=function(t){if(t==null)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var i=r(t);if(typeof i=="object")for(var n=i.length,o=0;o{"use strict";var Fl=A$(),Rm=(r,e)=>function(){return`[${r.apply(Fl,arguments)+e}m`},km=(r,e)=>function(){let t=r.apply(Fl,arguments);return`[${38+e};5;${t}m`},Im=(r,e)=>function(){let t=r.apply(Fl,arguments);return`[${38+e};2;${t[0]};${t[1]};${t[2]}m`};function Xfe(){let r=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.grey=e.color.gray;for(let n of Object.keys(e)){let o=e[n];for(let s of Object.keys(o)){let a=o[s];e[s]={open:`[${a[0]}m`,close:`[${a[1]}m`},o[s]=e[s],r.set(a[0],a[1])}Object.defineProperty(e,n,{value:o,enumerable:!1}),Object.defineProperty(e,"codes",{value:r,enumerable:!1})}let t=n=>n,i=(n,o,s)=>[n,o,s];e.color.close="",e.bgColor.close="",e.color.ansi={ansi:Rm(t,0)},e.color.ansi256={ansi256:km(t,0)},e.color.ansi16m={rgb:Im(i,0)},e.bgColor.ansi={ansi:Rm(t,10)},e.bgColor.ansi256={ansi256:km(t,10)},e.bgColor.ansi16m={rgb:Im(i,10)};for(let n of Object.keys(Fl)){if(typeof Fl[n]!="object")continue;let o=Fl[n];n==="ansi16"&&(n="ansi"),"ansi16"in o&&(e.color.ansi[n]=Rm(o.ansi16,0),e.bgColor.ansi[n]=Rm(o.ansi16,10)),"ansi256"in o&&(e.color.ansi256[n]=km(o.ansi256,0),e.bgColor.ansi256[n]=km(o.ansi256,10)),"rgb"in o&&(e.color.ansi16m[n]=Im(o.rgb,0),e.bgColor.ansi16m[n]=Im(o.rgb,10))}return e}Object.defineProperty(O$,"exports",{enumerable:!0,get:Xfe})});var N$=g((TTe,M$)=>{"use strict";M$.exports=(r,e)=>{e=e||process.argv;let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),n=e.indexOf("--");return i!==-1&&(n===-1?!0:i{"use strict";var Zfe=require("os"),Vi=N$(),sr=process.env,Al;Vi("no-color")||Vi("no-colors")||Vi("color=false")?Al=!1:(Vi("color")||Vi("colors")||Vi("color=true")||Vi("color=always"))&&(Al=!0);"FORCE_COLOR"in sr&&(Al=sr.FORCE_COLOR.length===0||parseInt(sr.FORCE_COLOR,10)!==0);function Qfe(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function epe(r){if(Al===!1)return 0;if(Vi("color=16m")||Vi("color=full")||Vi("color=truecolor"))return 3;if(Vi("color=256"))return 2;if(r&&!r.isTTY&&Al!==!0)return 0;let e=Al?1:0;if(process.platform==="win32"){let t=Zfe.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in sr)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(t=>t in sr)||sr.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in sr)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(sr.TEAMCITY_VERSION)?1:0;if(sr.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in sr){let t=parseInt((sr.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(sr.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(sr.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(sr.TERM)||"COLORTERM"in sr?1:(sr.TERM==="dumb",e)}function eD(r){let e=epe(r);return Qfe(e)}q$.exports={supportsColor:eD,stdout:eD(process.stdout),stderr:eD(process.stderr)}});var H$=g((kTe,B$)=>{"use strict";var tpe=/(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,j$=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,rpe=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,ipe=/\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi,npe=new Map([["n",` +`],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e",""],["a","\x07"]]);function U$(r){return r[0]==="u"&&r.length===5||r[0]==="x"&&r.length===3?String.fromCharCode(parseInt(r.slice(1),16)):npe.get(r)||r}function ope(r,e){let t=[],i=e.trim().split(/\s*,\s*/g),n;for(let o of i)if(!isNaN(o))t.push(Number(o));else if(n=o.match(rpe))t.push(n[2].replace(ipe,(s,a,l)=>a?U$(a):l));else throw new Error(`Invalid Chalk template style argument: ${o} (in style '${r}')`);return t}function spe(r){j$.lastIndex=0;let e=[],t;for(;(t=j$.exec(r))!==null;){let i=t[1];if(t[2]){let n=ope(i,t[2]);e.push([i].concat(n))}else e.push([i])}return e}function W$(r,e){let t={};for(let n of e)for(let o of n.styles)t[o[0]]=n.inverse?null:o.slice(1);let i=r;for(let n of Object.keys(t))if(Array.isArray(t[n])){if(!(n in i))throw new Error(`Unknown Chalk style: ${n}`);t[n].length>0?i=i[n].apply(i,t[n]):i=i[n]}return i}B$.exports=(r,e)=>{let t=[],i=[],n=[];if(e.replace(tpe,(o,s,a,l,u,c)=>{if(s)n.push(U$(s));else if(l){let f=n.join("");n=[],i.push(t.length===0?f:W$(r,t)(f)),t.push({inverse:a,styles:spe(l)})}else if(u){if(t.length===0)throw new Error("Found extraneous } in Chalk template literal");i.push(W$(r,t)(n.join(""))),n=[],t.pop()}else n.push(c)}),i.push(n.join("")),t.length>0){let o=`Chalk template literal is missing ${t.length} closing bracket${t.length===1?"":"s"} (\`}\`)`;throw new Error(o)}return i.join("")}});var J$=g((ITe,Ff)=>{"use strict";var tD=S$(),xt=L$(),rD=$$().stdout,ape=H$(),z$=process.platform==="win32"&&!(process.env.TERM||"").toLowerCase().startsWith("xterm"),G$=["ansi","ansi","ansi256","ansi16m"],V$=new Set(["gray"]),Ol=Object.create(null);function K$(r,e){e=e||{};let t=rD?rD.level:0;r.level=e.level===void 0?t:e.level,r.enabled="enabled"in e?e.enabled:r.level>0}function Af(r){if(!this||!(this instanceof Af)||this.template){let e={};return K$(e,r),e.template=function(){let t=[].slice.call(arguments);return lpe.apply(null,[e.template].concat(t))},Object.setPrototypeOf(e,Af.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=Af,e.template}K$(this,r)}z$&&(xt.blue.open="");for(let r of Object.keys(xt))xt[r].closeRe=new RegExp(tD(xt[r].close),"g"),Ol[r]={get(){let e=xt[r];return Fm.call(this,this._styles?this._styles.concat(e):[e],this._empty,r)}};Ol.visible={get(){return Fm.call(this,this._styles||[],!0,"visible")}};xt.color.closeRe=new RegExp(tD(xt.color.close),"g");for(let r of Object.keys(xt.color.ansi))V$.has(r)||(Ol[r]={get(){let e=this.level;return function(){let i={open:xt.color[G$[e]][r].apply(null,arguments),close:xt.color.close,closeRe:xt.color.closeRe};return Fm.call(this,this._styles?this._styles.concat(i):[i],this._empty,r)}}});xt.bgColor.closeRe=new RegExp(tD(xt.bgColor.close),"g");for(let r of Object.keys(xt.bgColor.ansi)){if(V$.has(r))continue;let e="bg"+r[0].toUpperCase()+r.slice(1);Ol[e]={get(){let t=this.level;return function(){let n={open:xt.bgColor[G$[t]][r].apply(null,arguments),close:xt.bgColor.close,closeRe:xt.bgColor.closeRe};return Fm.call(this,this._styles?this._styles.concat(n):[n],this._empty,r)}}}}var upe=Object.defineProperties(()=>{},Ol);function Fm(r,e,t){let i=function(){return cpe.apply(i,arguments)};i._styles=r,i._empty=e;let n=this;return Object.defineProperty(i,"level",{enumerable:!0,get(){return n.level},set(o){n.level=o}}),Object.defineProperty(i,"enabled",{enumerable:!0,get(){return n.enabled},set(o){n.enabled=o}}),i.hasGrey=this.hasGrey||t==="gray"||t==="grey",i.__proto__=upe,i}function cpe(){let r=arguments,e=r.length,t=String(arguments[0]);if(e===0)return"";if(e>1)for(let n=1;n{"use strict";Y$.exports=({onlyFirst:r=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,r?void 0:"g")}});var iD=g((ATe,Z$)=>{"use strict";var fpe=X$();Z$.exports=r=>typeof r=="string"?r.replace(fpe(),""):r});var eB=g((OTe,nD)=>{"use strict";var Q$=r=>Number.isNaN(r)?!1:r>=4352&&(r<=4447||r===9001||r===9002||11904<=r&&r<=12871&&r!==12351||12880<=r&&r<=19903||19968<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65131||65281<=r&&r<=65376||65504<=r&&r<=65510||110592<=r&&r<=110593||127488<=r&&r<=127569||131072<=r&&r<=262141);nD.exports=Q$;nD.exports.default=Q$});var rB=g((LTe,tB)=>{"use strict";tB.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var nB=g((MTe,oD)=>{"use strict";var ppe=iD(),dpe=eB(),hpe=rB(),iB=r=>{if(r=r.replace(hpe()," "),typeof r!="string"||r.length===0)return 0;r=ppe(r);let e=0;for(let t=0;t=127&&i<=159||i>=768&&i<=879||(i>65535&&t++,e+=dpe(i)?2:1)}return e};oD.exports=iB;oD.exports.default=iB});var sB=g(Ll=>{var mpe=nB();Ll.repeat=function(r,e){return Array(e+1).join(r)};Ll.pad=function(r,e,t,i){if(e+1>=r.length)switch(i){case"left":r=Array(e+1-r.length).join(t)+r;break;case"both":var n=Math.ceil((padlen=e-r.length)/2),o=padlen-n;r=Array(o+1).join(t)+r+Array(n+1).join(t);break;default:r=r+Array(e+1-r.length).join(t)}return r};Ll.truncate=function(r,e,t){return t=t||"\u2026",r.length>=e?r.substr(0,e-t.length)+t:r};function oB(r,e){for(var t in e)e[t]&&e[t].constructor&&e[t].constructor===Object?(r[t]=r[t]||{},oB(r[t],e[t])):r[t]=e[t];return r}Ll.options=oB;Ll.strlen=function(r){var e=/\u001b\[(?:\d*;){0,5}\d*m/g,t=(""+(r!=null?r:"")).replace(e,""),i=t.split(` +`);return i.reduce(function(n,o){var s=mpe(o);return s>n?s:n},0)}});var lB=g((qTe,aB)=>{aB.exports={name:"cli-table",description:"Pretty unicode tables for the CLI",version:"0.3.4",license:"MIT",author:"Guillermo Rauch ",contributors:["Sonny Michaud (http://github.com/sonnym)","Gabriel Sambarino (http://github.com/chrean)"],repository:{type:"git",url:"https://github.com/Automattic/cli-table.git"},keywords:["cli","colors","table"],dependencies:{chalk:"^2.4.1","string-width":"^4.2.0"},devDependencies:{"@babel/core":"^7.12.9","@babel/preset-env":"^7.12.7","@babel/preset-typescript":"^7.12.7","babel-jest":"^26.6.3",expect:"^26.6.2",expresso:"~0.9",jest:"^26.6.3","jest-mock":"^26.6.2","publish-please":"^5.5.2","ts-node":"^9.1.0",typescript:"^4.1.2"},main:"lib",files:["lib"],scripts:{test:"jest","publish-please":"publish-please --access public"},engines:{node:">= 10.0.0"}}});var uB=g(($Te,sD)=>{var gpe=J$(),Ys=sB(),aD=Ys.repeat,vpe=Ys.truncate,ype=Ys.pad;function Of(r){this.options=Ys.options({chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},truncate:"\u2026",colors:!0,colWidths:[],colAligns:[],style:{"padding-left":1,"padding-right":1,head:["red"],border:["white"],compact:!1},head:[]},r)}Of.prototype.__proto__=Array.prototype;Of.prototype.__defineGetter__("width",function(){var r=this.toString().split(` +`);return r.length?r[0].length:0});Of.prototype.render;Of.prototype.toString=function(){var r="",e=this.options,t=e.style,i=e.head,n=e.chars,o=e.truncate,s=e.colWidths||new Array(this.head.length),a=0;if(!i.length&&!this.length)return"";if(!s.length){var l=this.slice(0);i.length&&(l=l.concat([i])),l.forEach(function(v){if(Array.isArray(v)&&v.length)u(v);else{var x=Object.keys(v)[0],w=v[x];s[0]=Math.max(s[0]||0,c(x)||0),Array.isArray(w)&&w.length?u(w,1):s[1]=Math.max(s[1]||0,c(w)||0)}})}a=(s.length==1?s[0]:s.reduce(function(v,x){return v+x}))+s.length+1;function u(v,x){var x=x||0;v.forEach(function(w,E){s[E+x]=Math.max(s[E+x]||0,c(w)||0)})}function c(v){return typeof v=="object"&&v&&v.width!=null?v.width:(typeof v=="object"&&v!==null?Ys.strlen(v.text):Ys.strlen(v))+(t["padding-left"]||0)+(t["padding-right"]||0)}function f(v,x,w,E){var P=0,v=x+aD(v,a-2)+w;return s.forEach(function(k,_){_!=s.length-1&&(P+=k+1,v=v.substr(0,P)+E+v.substr(P+1))}),h(e.style.border,v)}function p(){var v=f(n.top,n["top-left"]||n.top,n["top-right"]||n.top,n["top-mid"]);v&&(r+=v+` +`)}function d(v,x){var w=[],E=0;if(!Array.isArray(v)&&typeof v=="object"){var P=Object.keys(v)[0],k=v[P],_=!0;Array.isArray(k)?(v=k,v.unshift(P)):v=[P,k]}v.forEach(function(L,R){var F=(L==null?"":L).toString().split(` +`).reduce(function(K,ae){return K.push(m(ae,R)),K},[]),q=F.length;q>E&&(E=q),w.push({contents:F,height:q})});var O=new Array(E);w.forEach(function(L,R){L.contents.forEach(function(K,ae){O[ae]||(O[ae]=[]),(x||_&&R===0&&e.style.head)&&(K=h(e.style.head,K)),O[ae].push(K)});for(var F=L.height,q=E;F0&&(I+=` +`+h(e.style.border,n.left)),I+=L.join(h(e.style.border,n.middle))+h(e.style.border,n.right)}),h(e.style.border,n.left)+I}function h(v,x){return x?(e.colors&&v.forEach(function(w){x=gpe[w](x)}),x):""}function m(v,x){var v=String(typeof v=="object"&&v.text?v.text:v),w=Ys.strlen(v),E=s[x]-(t["padding-left"]||0)-(t["padding-right"]||0),P=e.colAligns[x]||"left";return aD(" ",t["padding-left"]||0)+(w==E?v:w{"use strict";var fB=10,pB=(r=0)=>e=>`[${38+r};5;${e}m`,dB=(r=0)=>(e,t,i)=>`[${38+r};2;${e};${t};${i}m`;function bpe(){let r=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,i]of Object.entries(e)){for(let[n,o]of Object.entries(i))e[n]={open:`[${o[0]}m`,close:`[${o[1]}m`},i[n]=e[n],r.set(o[0],o[1]);Object.defineProperty(e,t,{value:i,enumerable:!1})}return Object.defineProperty(e,"codes",{value:r,enumerable:!1}),e.color.close="",e.bgColor.close="",e.color.ansi256=pB(),e.color.ansi16m=dB(),e.bgColor.ansi256=pB(fB),e.bgColor.ansi16m=dB(fB),e.rgbToAnsi256=(t,i,n)=>t===i&&i===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(i/255*5)+Math.round(n/255*5),e.hexToRgb=t=>{let i=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(t.toString(16));if(!i)return[0,0,0];let{colorString:n}=i.groups;n.length===3&&(n=n.split("").map(s=>s+s).join(""));let o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},e.hexToAnsi256=t=>e.rgbToAnsi256(...e.hexToRgb(t)),e}Object.defineProperty(cB,"exports",{enumerable:!0,get:bpe})});var o3=g((ZRe,jm)=>{"use strict";jm.exports=Vpe;jm.exports.format=i3;jm.exports.parse=n3;var Kpe=/\B(?=(\d{3})+(?!\d))/g,Jpe=/(?:\.0*|(\.[^0]+)0+)$/,$o={b:1,kb:1<<10,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},Ype=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function Vpe(r,e){return typeof r=="string"?n3(r):typeof r=="number"?i3(r,e):null}function i3(r,e){if(!Number.isFinite(r))return null;var t=Math.abs(r),i=e&&e.thousandsSeparator||"",n=e&&e.unitSeparator||"",o=e&&e.decimalPlaces!==void 0?e.decimalPlaces:2,s=Boolean(e&&e.fixedDecimals),a=e&&e.unit||"";(!a||!$o[a.toLowerCase()])&&(t>=$o.pb?a="PB":t>=$o.tb?a="TB":t>=$o.gb?a="GB":t>=$o.mb?a="MB":t>=$o.kb?a="KB":a="B");var l=r/$o[a.toLowerCase()],u=l.toFixed(o);return s||(u=u.replace(Jpe,"$1")),i&&(u=u.replace(Kpe,i)),u+n+a}function n3(r){if(typeof r=="number"&&!isNaN(r))return r;if(typeof r!="string")return null;var e=Ype.exec(r),t,i="b";return e?(t=parseFloat(e[1]),i=e[4].toLowerCase()):(t=parseInt(r,10),i="b"),Math.floor($o[i]*t)}});var Bl=g((QRe,s3)=>{var vn=-1,Yi=1,Ir=0;function Bf(r,e,t,i){if(r===e)return r?[[Ir,r]]:[];if(t!=null){var n=Zpe(r,e,t);if(n)return n}var o=RD(r,e),s=r.substring(0,o);r=r.substring(o),e=e.substring(o),o=kD(r,e);var a=r.substring(r.length-o);r=r.substring(0,r.length-o),e=e.substring(0,e.length-o);var l=Xpe(r,e);return s&&l.unshift([Ir,s]),a&&l.push([Ir,a]),a3(l,i),l}function Xpe(r,e){var t;if(!r)return[[Yi,e]];if(!e)return[[vn,r]];var i=r.length>e.length?r:e,n=r.length>e.length?e:r,o=i.indexOf(n);if(o!==-1)return t=[[Yi,i.substring(0,o)],[Ir,n],[Yi,i.substring(o+n.length)]],r.length>e.length&&(t[0][0]=t[2][0]=vn),t;if(n.length===1)return[[vn,r],[Yi,e]];var s=ede(r,e);if(s){var a=s[0],l=s[1],u=s[2],c=s[3],f=s[4],p=Bf(a,u),d=Bf(l,c);return p.concat([[Ir,f]],d)}return Qpe(r,e)}function Qpe(r,e){for(var t=r.length,i=e.length,n=Math.ceil((t+i)/2),o=n,s=2*n,a=new Array(s),l=new Array(s),u=0;ut)d+=2;else if(E>i)p+=2;else if(f){var P=o+c-v;if(P>=0&&P=k)return l3(r,e,w,E)}}}for(var _=-y+h;_<=y-m;_+=2){var P=o+_,k;_===-y||_!==y&&l[P-1]t)m+=2;else if(O>i)h+=2;else if(!f){var x=o+c-_;if(x>=0&&x=k)return l3(r,e,w,E)}}}}return[[vn,r],[Yi,e]]}function l3(r,e,t,i){var n=r.substring(0,t),o=e.substring(0,i),s=r.substring(t),a=e.substring(i),l=Bf(n,o),u=Bf(s,a);return l.concat(u)}function RD(r,e){if(!r||!e||r.charAt(0)!==e.charAt(0))return 0;for(var t=0,i=Math.min(r.length,e.length),n=i,o=0;te.length?r:e,i=r.length>e.length?e:r;if(t.length<4||i.length*2=d.length?[w,E,P,k,x]:null}var o=n(t,i,Math.ceil(t.length/4)),s=n(t,i,Math.ceil(t.length/2)),a;if(!o&&!s)return null;s?o?a=o[4].length>s[4].length?o:s:a=s:a=o;var l,u,c,f;r.length>e.length?(l=a[0],u=a[1],c=a[2],f=a[3]):(c=a[0],f=a[1],l=a[2],u=a[3]);var p=a[4];return[l,u,c,f,p]}function a3(r,e){r.push([Ir,""]);for(var t=0,i=0,n=0,o="",s="",a;t=0&&p3(r[l][1])){var u=r[l][1].slice(-1);if(r[l][1]=r[l][1].slice(0,-1),o=u+o,s=u+s,!r[l][1]){r.splice(l,1),t--;var c=l-1;r[c]&&r[c][0]===Yi&&(n++,s=r[c][1]+s,c--),r[c]&&r[c][0]===vn&&(i++,o=r[c][1]+o,c--),l=c}}if(f3(r[t][1])){var u=r[t][1].charAt(0);r[t][1]=r[t][1].slice(1),o+=u,s+=u}}if(t0||s.length>0){o.length>0&&s.length>0&&(a=RD(s,o),a!==0&&(l>=0?r[l][1]+=s.substring(0,a):(r.splice(0,0,[Ir,s.substring(0,a)]),t++),s=s.substring(a),o=o.substring(a)),a=kD(s,o),a!==0&&(r[t][1]=s.substring(s.length-a)+r[t][1],s=s.substring(0,s.length-a),o=o.substring(0,o.length-a)));var f=n+i;o.length===0&&s.length===0?(r.splice(t-f,f),t=t-f):o.length===0?(r.splice(t-f,f,[Yi,s]),t=t-f+1):s.length===0?(r.splice(t-f,f,[vn,o]),t=t-f+1):(r.splice(t-f,f,[vn,o],[Yi,s]),t=t-f+2)}t!==0&&r[t-1][0]===Ir?(r[t-1][1]+=r[t][1],r.splice(t,1)):t++,n=0,i=0,o="",s="";break}}r[r.length-1][1]===""&&r.pop();var p=!1;for(t=1;t=55296&&r<=56319}function c3(r){return r>=56320&&r<=57343}function f3(r){return c3(r.charCodeAt(0))}function p3(r){return u3(r.charCodeAt(r.length-1))}function tde(r){for(var e=[],t=0;t0&&e.push(r[t]);return e}function ID(r,e,t,i){return p3(r)||f3(i)?null:tde([[Ir,r],[vn,e],[Yi,t],[Ir,i]])}function Zpe(r,e,t){var i=typeof t=="number"?{index:t,length:0}:t.oldRange,n=typeof t=="number"?null:t.newRange,o=r.length,s=e.length;if(i.length===0&&(n===null||n.length===0)){var a=i.index,l=r.slice(0,a),u=r.slice(a),c=n?n.index:null;e:{var f=a+s-o;if(c!==null&&c!==f||f<0||f>s)break e;var p=e.slice(0,f),d=e.slice(f);if(d!==u)break e;var h=Math.min(a,f),m=l.slice(0,h),y=p.slice(0,h);if(m!==y)break e;var v=l.slice(h),x=p.slice(h);return ID(m,v,x,u)}e:{if(c!==null&&c!==a)break e;var w=a,p=e.slice(0,w),d=e.slice(w);if(p!==l)break e;var E=Math.min(o-w,s-w),P=u.slice(u.length-E),k=d.slice(d.length-E);if(P!==k)break e;var v=u.slice(0,u.length-E),x=d.slice(0,d.length-E);return ID(l,v,x,P)}}if(i.length>0&&n&&n.length===0){e:{var m=r.slice(0,i.index),P=r.slice(i.index+i.length),h=m.length,E=P.length;if(s{_3.exports=function(r,e){for(var t=[],i=0;i{"use strict";T3.exports=R3;function R3(r,e,t){r instanceof RegExp&&(r=k3(r,t)),e instanceof RegExp&&(e=k3(e,t));var i=I3(r,e,t);return i&&{start:i[0],end:i[1],pre:t.slice(0,i[0]),body:t.slice(i[0]+r.length,i[1]),post:t.slice(i[1]+e.length)}}function k3(r,e){var t=e.match(r);return t?t[0]:null}R3.range=I3;function I3(r,e,t){var i,n,o,s,a,l=t.indexOf(r),u=t.indexOf(e,l+1),c=l;if(l>=0&&u>0){for(i=[],o=t.length;c>=0&&!a;)c==l?(i.push(c),l=t.indexOf(r,c+1)):i.length==1?a=[i.pop(),u]:(n=i.pop(),n=0?l:u;i.length&&(a=[o,s])}return a}});var B3=g((M1e,A3)=>{var fde=P3(),O3=F3();A3.exports=pde;var L3="\0SLASH"+Math.random()+"\0",M3="\0OPEN"+Math.random()+"\0",$D="\0CLOSE"+Math.random()+"\0",N3="\0COMMA"+Math.random()+"\0",q3="\0PERIOD"+Math.random()+"\0";function BD(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function dde(r){return r.split("\\\\").join(L3).split("\\{").join(M3).split("\\}").join($D).split("\\,").join(N3).split("\\.").join(q3)}function hde(r){return r.split(L3).join("\\").split(M3).join("{").split($D).join("}").split(N3).join(",").split(q3).join(".")}function $3(r){if(!r)return[""];var e=[],t=O3("{","}",r);if(!t)return r.split(",");var i=t.pre,n=t.body,o=t.post,s=i.split(",");s[s.length-1]+="{"+n+"}";var a=$3(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function pde(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Wl(dde(r),!0).map(hde)):[]}function mde(r){return"{"+r+"}"}function gde(r){return/^-?0\d/.test(r)}function vde(r,e){return r<=e}function yde(r,e){return r>=e}function Wl(r,e){var t=[],i=O3("{","}",r);if(!i||/\$$/.test(i.pre))return[r];var n=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),o=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),s=n||o,a=i.body.indexOf(",")>=0;if(!s&&!a)return i.post.match(/,.*\}/)?(r=i.pre+"{"+i.body+$D+i.post,Wl(r)):[r];var l;if(s)l=i.body.split(/\.\./);else if(l=$3(i.body),l.length===1&&(l=Wl(l[0],!1).map(mde),l.length===1)){var c=i.post.length?Wl(i.post,!1):[""];return c.map(function(R){return i.pre+l[0]+R})}var u=i.pre,c=i.post.length?Wl(i.post,!1):[""],f;if(s){var p=BD(l[0]),d=BD(l[1]),h=Math.max(l[0].length,l[1].length),m=l.length==3?Math.abs(BD(l[2])):1,y=vde,v=d0){var k=new Array(P+1).join("0");w<0?E="-"+k+E.slice(1):E=k+E}}f.push(E)}}else f=fde(l,function(L){return Wl(L,!1)});for(var _=0;_{j3.exports=Ei;Ei.Minimatch=At;var Vf={sep:"/"};try{Vf=require("path")}catch(r){}var jD=Ei.GLOBSTAR=At.GLOBSTAR={},bde=B3(),U3={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},UD="[^/]",WD=UD+"*?",wde="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",xde="(?:(?!(?:\\/|^)\\.).)*?",W3=Dde("().*{}+?[]^$\\!");function Dde(r){return r.split("").reduce(function(e,t){return e[t]=!0,e},{})}var H3=/\/+/;Ei.filter=Sde;function Sde(r,e){return e=e||{},function(t,i,n){return Ei(t,r,e)}}function z3(r,e){r=r||{},e=e||{};var t={};return Object.keys(e).forEach(function(i){t[i]=e[i]}),Object.keys(r).forEach(function(i){t[i]=r[i]}),t}Ei.defaults=function(r){if(!r||!Object.keys(r).length)return Ei;var e=Ei,t=function(n,o,s){return e.minimatch(n,o,z3(r,s))};return t.Minimatch=function(n,o){return new e.Minimatch(n,z3(r,o))},t};At.defaults=function(r){return!r||!Object.keys(r).length?At:Ei.defaults(r).Minimatch};function Ei(r,e,t){if(typeof e!="string")throw new TypeError("glob pattern string required");return t||(t={}),!t.nocomment&&e.charAt(0)==="#"?!1:e.trim()===""?r==="":new At(e,t).match(r)}function At(r,e){if(!(this instanceof At))return new At(r,e);if(typeof r!="string")throw new TypeError("glob pattern string required");e||(e={}),r=r.trim(),Vf.sep!=="/"&&(r=r.split(Vf.sep).join("/")),this.options=e,this.set=[],this.pattern=r,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}At.prototype.debug=function(){};At.prototype.make=Ede;function Ede(){if(!this._made){var r=this.pattern,e=this.options;if(!e.nocomment&&r.charAt(0)==="#"){this.comment=!0;return}if(!r){this.empty=!0;return}this.parseNegate();var t=this.globSet=this.braceExpand();e.debug&&(this.debug=console.error),this.debug(this.pattern,t),t=this.globParts=t.map(function(i){return i.split(H3)}),this.debug(this.pattern,t),t=t.map(function(i,n,o){return i.map(this.parse,this)},this),this.debug(this.pattern,t),t=t.filter(function(i){return i.indexOf(!1)===-1}),this.debug(this.pattern,t),this.set=t}}At.prototype.parseNegate=Cde;function Cde(){var r=this.pattern,e=!1,t=this.options,i=0;if(!t.nonegate){for(var n=0,o=r.length;n1024*64)throw new TypeError("pattern is too long");var t=this.options;if(!t.noglobstar&&r==="**")return jD;if(r==="")return"";var i="",n=!!t.nocase,o=!1,s=[],a=[],l,u=!1,c=-1,f=-1,p=r.charAt(0)==="."?"":t.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",d=this;function h(){if(l){switch(l){case"*":i+=WD,n=!0;break;case"?":i+=UD,n=!0;break;default:i+="\\"+l;break}d.debug("clearStateChar %j %j",l,i),l=!1}}for(var m=0,y=r.length,v;m-1;O--){var I=a[O],L=i.slice(0,I.reStart),R=i.slice(I.reStart,I.reEnd-8),F=i.slice(I.reEnd-8,I.reEnd),q=i.slice(I.reEnd);F+=q;var K=L.split("(").length-1,ae=q;for(m=0;m=0&&(n=r[o],!n);o--);for(o=0;o>> no match, partial?`,r,c,e,f),c===s))}var d;if(typeof l=="string"?(i.nocase?d=u.toLowerCase()===l.toLowerCase():d=u===l,this.debug("string match",l,u,d)):(d=u.match(l),this.debug("pattern match",l,u,d)),!d)return!1}if(n===s&&o===a)return!0;if(n===s)return t;if(o===a){var h=n===s-1&&r[n]==="";return h}throw new Error("wtf?")};function Pde(r){return r.replace(/\\(.)/g,"$1")}function Rde(r){return r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var gj=g((sIe,hj)=>{var p0=4294967296,mj=[];for(var ep=0;ep<256;ep++)mj[ep]=(ep>15?"":"0")+ep.toString(16);var tp=hj.exports=function(r,e){r instanceof Buffer?(this.buffer=r,this.offset=e||0):Object.prototype.toString.call(r)=="[object Uint8Array]"?(this.buffer=new Buffer(r),this.offset=e||0):(this.buffer=this.buffer||new Buffer(8),this.offset=0,this.setValue.apply(this,arguments))};tp.MAX_INT=Math.pow(2,53);tp.MIN_INT=-Math.pow(2,53);tp.prototype={constructor:tp,_2scomp:function(){for(var r=this.buffer,e=this.offset,t=1,i=e+7;i>=e;i--){var n=(r[i]^255)+t;r[i]=n&255,t=n>>8}},setValue:function(r,e){var t=!1;if(arguments.length==1)if(typeof r=="number"){if(t=r<0,r=Math.abs(r),e=r%p0,r=r/p0,r>p0)throw new RangeError(r+" is outside Int64 range");r=r|0}else if(typeof r=="string")r=(r+"").replace(/^0x/,""),e=r.substr(-8),r=r.length>8?r.substr(0,r.length-8):"",r=parseInt(r,16),e=parseInt(e,16);else throw new Error(r+" must be a Number or String");for(var i=this.buffer,n=this.offset,o=7;o>=0;o--)i[n+o]=e&255,e=o==4?r:e>>>8;t&&this._2scomp()},toNumber:function(r){for(var e=this.buffer,t=this.offset,i=e[t]&128,n=0,o=1,s=7,a=1;s>=0;s--,a*=256){var l=e[t+s];i&&(l=(l^255)+o,o=l>>8,l=l&255),n+=l*a}return!r&&n>=tp.MAX_INT?i?-Infinity:Infinity:i?-n:n},valueOf:function(){return this.toNumber(!1)},toString:function(r){return this.valueOf().toString(r||10)},toOctetString:function(r){for(var e=new Array(8),t=this.buffer,i=this.offset,n=0;n<8;n++)e[n]=mj[t[i+n]];return e.join(r||"")},toBuffer:function(r){if(r&&this.offset===0)return this.buffer;var e=new Buffer(8);return this.buffer.copy(e,0,this.offset,this.offset+8),e},copy:function(r,e){this.buffer.copy(r,e||0,this.offset,this.offset+8)},compare:function(r){if((this.buffer[this.offset]&128)!=(r.buffer[r.offset]&128))return r.buffer[r.offset]-this.buffer[this.offset];for(var e=0;e<8;e++)if(this.buffer[this.offset+e]!==r.buffer[r.offset+e])return this.buffer[this.offset+e]-r.buffer[r.offset+e];return 0},equals:function(r){return this.compare(r)===0},inspect:function(){return"[Int64 value:"+this+" octets:"+this.toOctetString(" ")+"]"}}});var Pj=g(rp=>{var vj=require("events").EventEmitter,Mde=require("util"),Nde=require("os"),aIe=require("assert"),ip=gj(),Wo=Nde.endianness()=="BE";function yj(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function Ot(r){this.buf=Buffer.alloc(yj(r||8192)),this.readOffset=0,this.writeOffset=0}rp.Accumulator=Ot;Ot.prototype.writeAvail=function(){return this.buf.length-this.writeOffset};Ot.prototype.readAvail=function(){return this.writeOffset-this.readOffset};Ot.prototype.reserve=function(r){if(!(r0&&(this.buf.copy(this.buf,0,this.readOffset,this.writeOffset),this.writeOffset-=this.readOffset,this.readOffset=0),!(r0)this.assertReadableSize(r);else if(r<0&&this.readOffset+r<0)throw new Error("advance with negative offset "+r+" would seek off the start of the buffer");this.readOffset+=r};Ot.prototype.writeByte=function(r){this.reserve(1),this.buf.writeInt8(r,this.writeOffset),++this.writeOffset};Ot.prototype.writeInt=function(r,e){switch(this.reserve(e),e){case 1:this.buf.writeInt8(r,this.writeOffset);break;case 2:Wo?this.buf.writeInt16BE(r,this.writeOffset):this.buf.writeInt16LE(r,this.writeOffset);break;case 4:Wo?this.buf.writeInt32BE(r,this.writeOffset):this.buf.writeInt32LE(r,this.writeOffset);break;default:throw new Error("unsupported integer size "+e)}this.writeOffset+=e};Ot.prototype.writeDouble=function(r){this.reserve(8),Wo?this.buf.writeDoubleBE(r,this.writeOffset):this.buf.writeDoubleLE(r,this.writeOffset),this.writeOffset+=8};var d0=0,h0=1,m0=2,g0=3,v0=4,ig=5,ng=6,wj=7,xj=8,Dj=9,Sj=10,Ej=11,qde=12,y0=0,Cj=1,$de=127,Bde=32767,jde=2147483647;function Ar(){vj.call(this),this.buf=new Ot,this.state=y0}Mde.inherits(Ar,vj);rp.BunserBuf=Ar;Ar.prototype.append=function(r,e){if(e)return this.buf.append(r),this.process(e);try{this.buf.append(r)}catch(t){this.emit("error",t);return}this.processLater()};Ar.prototype.processLater=function(){var r=this;process.nextTick(function(){try{r.process(!1)}catch(e){r.emit("error",e)}})};Ar.prototype.process=function(r){if(this.state==y0){if(this.buf.readAvail()<2)return;if(this.expectCode(0),this.expectCode(1),this.pduLen=this.decodeInt(!0),this.pduLen===!1){this.buf.readAdvance(-2);return}this.buf.reserve(this.pduLen),this.state=Cj}if(this.state==Cj){if(this.buf.readAvail()0&&this.processLater()};Ar.prototype.raise=function(r){throw new Error(r+", in Buffer of length "+this.buf.buf.length+" ("+this.buf.readAvail()+" readable) at offset "+this.buf.readOffset+" buffer: "+JSON.stringify(this.buf.buf.slice(this.buf.readOffset,this.buf.readOffset+32).toJSON()))};Ar.prototype.expectCode=function(r){var e=this.buf.readInt(1);e!=r&&this.raise("expected bser opcode "+r+" but got "+e)};Ar.prototype.decodeAny=function(){var r=this.buf.peekInt(1);switch(r){case g0:case v0:case ig:case ng:return this.decodeInt();case wj:return this.buf.readAdvance(1),this.buf.readDouble();case xj:return this.buf.readAdvance(1),!0;case Dj:return this.buf.readAdvance(1),!1;case Sj:return this.buf.readAdvance(1),null;case m0:return this.decodeString();case d0:return this.decodeArray();case h0:return this.decodeObject();case Ej:return this.decodeTemplate();default:this.raise("unhandled bser opcode "+r)}};Ar.prototype.decodeArray=function(){this.expectCode(d0);for(var r=this.decodeInt(),e=[],t=0;t{"use strict";var Hde=require("net"),Rj=require("events").EventEmitter,zde=require("util"),Gde=require("child_process"),kj=Pj(),Ij=["subscription","log"];function Vn(r){var e=this;Rj.call(this),this.watchmanBinaryPath="watchman",r&&r.watchmanBinaryPath&&(this.watchmanBinaryPath=r.watchmanBinaryPath.trim()),this.commands=[]}zde.inherits(Vn,Rj);Tj.exports.Client=Vn;Vn.prototype.sendNextCommand=function(){this.currentCommand||(this.currentCommand=this.commands.shift(),!!this.currentCommand&&this.socket.write(kj.dumpToBuffer(this.currentCommand.cmd)))};Vn.prototype.cancelCommands=function(r){var e=new Error(r),t=this.commands;this.commands=[],this.currentCommand&&(t.unshift(this.currentCommand),this.currentCommand=null),t.forEach(function(i){i.cb(e)})};Vn.prototype.connect=function(){var r=this;function e(l){r.bunser=new kj.BunserBuf,r.bunser.on("value",function(u){for(var c=!1,f=0;f=0:!1}Vn.prototype._synthesizeCapabilityCheck=function(r,e,t){r.capabilities={};var i=r.version;return e.forEach(function(n){r.capabilities[n]=Aj(i,n)}),t.forEach(function(n){var o=Aj(i,n);r.capabilities[n]=o,o||(r.error="client required capability `"+n+"` is not supported by this server")}),r};Vn.prototype.capabilityCheck=function(r,e){var t=r.optional||[],i=r.required||[],n=this;this.command(["version",{optional:t,required:i}],function(o,s){if(o){e(o);return}if(!("capabilities"in s)&&(s=n._synthesizeCapabilityCheck(s,t,i),s.error)){o=new Error(s.error),o.watchmanResponse=s,e(o);return}e(null,s)})};Vn.prototype.end=function(){this.cancelCommands("The client was ended"),this.socket&&(this.socket.end(),this.socket=null),this.bunser=null}});var oU=g(ia=>{ia.parse=ia.decode=ihe;ia.stringify=ia.encode=rU;ia.safe=Yl;ia.unsafe=hg;var k0=typeof process!="undefined"&&process.platform==="win32"?`\r +`:` +`;function rU(r,e){var t=[],i="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||{},e.whitespace=e.whitespace===!0);var n=e.whitespace?" = ":"=";return Object.keys(r).forEach(function(o,s,a){var l=r[o];l&&Array.isArray(l)?l.forEach(function(u){i+=Yl(o+"[]")+n+Yl(u)+` +`}):l&&typeof l=="object"?t.push(o):i+=Yl(o)+n+Yl(l)+k0}),e.section&&i.length&&(i="["+Yl(e.section)+"]"+k0+i),t.forEach(function(o,s,a){var l=iU(o).join("\\."),u=(e.section?e.section+".":"")+l,c=rU(r[o],{section:u,whitespace:e.whitespace});i.length&&c.length&&(i+=k0),i+=c}),i}function iU(r){return r.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(function(e){return e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")})}function ihe(r){var e={},t=e,i=null,n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,o=r.split(/[\r\n]+/g);return o.forEach(function(s,a,l){if(!(!s||s.match(/^\s*[;#]/))){var u=s.match(n);if(!!u){if(u[1]!==void 0){i=hg(u[1]),t=e[i]=e[i]||{};return}var c=hg(u[2]),f=u[3]?hg(u[4]):!0;switch(f){case"true":case"false":case"null":f=JSON.parse(f)}c.length>2&&c.slice(-2)==="[]"&&(c=c.substring(0,c.length-2),t[c]?Array.isArray(t[c])||(t[c]=[t[c]]):t[c]=[]),Array.isArray(t[c])?t[c].push(f):t[c]=f}}}),Object.keys(e).filter(function(s,a,l){if(!e[s]||typeof e[s]!="object"||Array.isArray(e[s]))return!1;var u=iU(s),c=e,f=u.pop(),p=f.replace(/\\\./g,".");return u.forEach(function(d,h,m){(!c[d]||typeof c[d]!="object")&&(c[d]={}),c=c[d]}),c===e&&p===f?!1:(c[p]=e[s],!0)}).forEach(function(s,a,l){delete e[s]}),e}function nU(r){return r.charAt(0)==='"'&&r.slice(-1)==='"'||r.charAt(0)==="'"&&r.slice(-1)==="'"}function Yl(r){return typeof r!="string"||r.match(/[=\r\n]/)||r.match(/^\[/)||r.length>1&&nU(r)||r!==r.trim()?JSON.stringify(r):r.replace(/;/g,"\\;").replace(/#/g,"\\#")}function hg(r,e){if(r=(r||"").trim(),nU(r)){r.charAt(0)==="'"&&(r=r.substr(1,r.length-2));try{r=JSON.parse(r)}catch(a){}}else{for(var t=!1,i="",n=0,o=r.length;n{"use strict";var I0=1,aU=2;function nhe(){return""}function ohe(r,e,t){return r.slice(e,t).replace(/\S/g," ")}sU.exports=function(r,e){e=e||{};for(var t,i,n=!1,o=!1,s=0,a="",l=e.whitespace===!1?nhe:ohe,u=0;u{"use strict";var uU=require("fs"),she=oU(),up=require("path"),ahe=lU(),lhe=Xl.parse=function(r){return/^\s*{/.test(r)?JSON.parse(ahe(r)):she.parse(r)},uhe=Xl.file=function(){var r=[].slice.call(arguments).filter(function(n){return n!=null});for(var e in r)if(typeof r[e]!="string")return;var t=up.join.apply(null,r),i;try{return uU.readFileSync(t,"utf-8")}catch(n){return}},AAe=Xl.json=function(){var r=uhe.apply(null,arguments);return r?lhe(r):null},OAe=Xl.env=function(r,e){e=e||process.env;var t={},i=r.length;for(var n in e)if(n.toLowerCase().indexOf(r.toLowerCase())===0){for(var o=n.substring(i).split("__"),s;(s=o.indexOf(""))>-1;)o.splice(s,1);var a=t;o.forEach(function(u,c){!u||typeof a!="object"||(c===o.length-1&&(a[u]=e[n]),a[u]===void 0&&(a[u]={}),a=a[u])})}return t},LAe=Xl.find=function(){var r=up.join.apply(null,[].slice.call(arguments));function e(t,i){var n=up.join(t,i);try{return uU.statSync(n),n}catch(o){if(up.dirname(t)!==t)return e(up.dirname(t),i)}}return e(process.cwd(),r)}});var gU=g((NAe,fU)=>{"use strict";function pU(r){return r instanceof Buffer||r instanceof Date||r instanceof RegExp}function dU(r){if(r instanceof Buffer){var e=Buffer.alloc?Buffer.alloc(r.length):new Buffer(r.length);return r.copy(e),e}else{if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp)return new RegExp(r);throw new Error("Unexpected situation")}}function hU(r){var e=[];return r.forEach(function(t,i){typeof t=="object"&&t!==null?Array.isArray(t)?e[i]=hU(t):pU(t)?e[i]=dU(t):e[i]=F0({},t):e[i]=t}),e}function mU(r,e){return e==="__proto__"?void 0:r[e]}var F0=fU.exports=function(){if(arguments.length<1||typeof arguments[0]!="object")return!1;if(arguments.length<2)return arguments[0];var r=arguments[0],e=Array.prototype.slice.call(arguments,1),t,i,n;return e.forEach(function(o){typeof o!="object"||o===null||Array.isArray(o)||Object.keys(o).forEach(function(s){if(i=mU(r,s),t=mU(o,s),t!==r)if(typeof t!="object"||t===null){r[s]=t;return}else if(Array.isArray(t)){r[s]=hU(t);return}else if(pU(t)){r[s]=dU(t);return}else if(typeof i!="object"||i===null||Array.isArray(i)){r[s]=F0({},t);return}else{r[s]=F0(i,t);return}})}),r}});var bU=g((qAe,vU)=>{vU.exports=function(r,e){e||(e={});var t={bools:{},strings:{},unknownFn:null};typeof e.unknown=="function"&&(t.unknownFn=e.unknown),typeof e.boolean=="boolean"&&e.boolean?t.allBools=!0:[].concat(e.boolean).filter(Boolean).forEach(function(E){t.bools[E]=!0});var i={};Object.keys(e.alias||{}).forEach(function(E){i[E]=[].concat(e.alias[E]),i[E].forEach(function(P){i[P]=[E].concat(i[E].filter(function(k){return P!==k}))})}),[].concat(e.string).filter(Boolean).forEach(function(E){t.strings[E]=!0,i[E]&&(t.strings[i[E]]=!0)});var n=e.default||{},o={_:[]};Object.keys(t.bools).forEach(function(E){l(E,n[E]===void 0?!1:n[E])});var s=[];r.indexOf("--")!==-1&&(s=r.slice(r.indexOf("--")+1),r=r.slice(0,r.indexOf("--")));function a(E,P){return t.allBools&&/^--[^=]+$/.test(P)||t.strings[E]||t.bools[E]||i[E]}function l(E,P,k){if(!(k&&t.unknownFn&&!a(E,k)&&t.unknownFn(k)===!1)){var _=!t.strings[E]&&yU(P)?Number(P):P;u(o,E.split("."),_),(i[E]||[]).forEach(function(O){u(o,O.split("."),_)})}}function u(E,P,k){for(var _=E,O=0;O{var cp=cU(),Zl=require("path").join,fhe=gU(),xU="/etc",DU=process.platform==="win32",fp=DU?process.env.USERPROFILE:process.env.HOME;wU.exports=function(r,e,t,i){if(typeof r!="string")throw new Error("rc(name): name *must* be string");t||(t=bU()(process.argv.slice(2))),e=(typeof e=="string"?cp.json(e):e)||{},i=i||cp.parse;var n=cp.env(r+"_"),o=[e],s=[];function a(l){if(!(s.indexOf(l)>=0)){var u=cp.file(l);u&&(o.push(i(u)),s.push(l))}}return DU||[Zl(xU,r,"config"),Zl(xU,r+"rc")].forEach(a),fp&&[Zl(fp,".config",r,"config"),Zl(fp,".config",r),Zl(fp,"."+r,"config"),Zl(fp,"."+r+"rc")].forEach(a),a(cp.find("."+r+"rc")),n.config&&a(n.config),t.config&&a(t.config),fhe.apply(null,o.concat([n,t,s.length?{configs:s,config:s[s.length-1]}:void 0]))}});var _U=g((A0,EU)=>{var mg=require("buffer"),Kn=mg.Buffer;function CU(r,e){for(var t in r)e[t]=r[t]}Kn.from&&Kn.alloc&&Kn.allocUnsafe&&Kn.allocUnsafeSlow?EU.exports=mg:(CU(mg,A0),A0.Buffer=Ql);function Ql(r,e,t){return Kn(r,e,t)}CU(Kn,Ql);Ql.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return Kn(r,e,t)};Ql.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var i=Kn(r);return e!==void 0?typeof t=="string"?i.fill(e,t):i.fill(e):i.fill(0),i};Ql.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Kn(r)};Ql.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return mg.SlowBuffer(r)}});var FU=g((BAe,O0)=>{"use strict";O0.exports=phe;O0.exports.parse=dhe;var PU=require("path").basename,hhe=_U().Buffer,mhe=/[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g,ghe=/%[0-9A-Fa-f]{2}/,vhe=/%([0-9A-Fa-f]{2})/g,TU=/[^\x20-\x7e\xa0-\xff]/g,yhe=/\\([\u0000-\u007f])/g,bhe=/([\\"])/g,RU=/;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g,whe=/^[\x20-\x7e\x80-\xff]+$/,xhe=/^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/,Dhe=/^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/,She=/^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;function phe(r,e){var t=e||{},i=t.type||"attachment",n=Ehe(r,t.fallback);return Che(new kU(i,n))}function Ehe(r,e){if(r!==void 0){var t={};if(typeof r!="string")throw new TypeError("filename must be a string");if(e===void 0&&(e=!0),typeof e!="string"&&typeof e!="boolean")throw new TypeError("fallback must be a string or boolean");if(typeof e=="string"&&TU.test(e))throw new TypeError("fallback must be ISO-8859-1 string");var i=PU(r),n=whe.test(i),o=typeof e!="string"?e&&IU(i):PU(e),s=typeof o=="string"&&o!==i;return(s||!n||ghe.test(i))&&(t["filename*"]=i),(n||s)&&(t.filename=s?o:i),t}}function Che(r){var e=r.parameters,t=r.type;if(!t||typeof t!="string"||!xhe.test(t))throw new TypeError("invalid type");var i=String(t).toLowerCase();if(e&&typeof e=="object")for(var n,o=Object.keys(e).sort(),s=0;s{var L0;try{L0=gt()("follow-redirects")}catch(r){L0=function(){}}AU.exports=L0});var B0=g((UAe,M0)=>{var eu=require("url"),N0=eu.URL,Ihe=require("http"),Fhe=require("https"),LU=require("stream").Writable,Ahe=require("assert"),MU=OU(),q0=Object.create(null);["abort","aborted","connect","error","socket","timeout"].forEach(function(r){q0[r]=function(e,t,i){this._redirectable.emit(r,e,t,i)}});var Ohe=gg("ERR_FR_REDIRECTION_FAILURE",""),Lhe=gg("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded"),Mhe=gg("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),Nhe=gg("ERR_STREAM_WRITE_AFTER_END","write after end");function Ti(r,e){LU.call(this),this._sanitizeOptions(r),this._options=r,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],e&&this.on("response",e);var t=this;this._onNativeResponse=function(i){t._processResponse(i)},this._performRequest()}Ti.prototype=Object.create(LU.prototype);Ti.prototype.write=function(r,e,t){if(this._ending)throw new Nhe;if(!(typeof r=="string"||typeof r=="object"&&"length"in r))throw new TypeError("data should be a string, Buffer or Uint8Array");if(typeof e=="function"&&(t=e,e=null),r.length===0){t&&t();return}this._requestBodyLength+r.length<=this._options.maxBodyLength?(this._requestBodyLength+=r.length,this._requestBodyBuffers.push({data:r,encoding:e}),this._currentRequest.write(r,e,t)):(this.emit("error",new Mhe),this.abort())};Ti.prototype.end=function(r,e,t){if(typeof r=="function"?(t=r,r=e=null):typeof e=="function"&&(t=e,e=null),!r)this._ended=this._ending=!0,this._currentRequest.end(null,null,t);else{var i=this,n=this._currentRequest;this.write(r,e,function(){i._ended=!0,n.end(null,null,t)}),this._ending=!0}};Ti.prototype.setHeader=function(r,e){this._options.headers[r]=e,this._currentRequest.setHeader(r,e)};Ti.prototype.removeHeader=function(r){delete this._options.headers[r],this._currentRequest.removeHeader(r)};Ti.prototype.setTimeout=function(r,e){if(e&&this.once("timeout",e),this.socket)NU(this,r);else{var t=this;this._currentRequest.once("socket",function(){NU(t,r)})}return this.once("response",qU),this.once("error",qU),this};function NU(r,e){clearTimeout(r._timeout),r._timeout=setTimeout(function(){r.emit("timeout")},e)}function qU(){clearTimeout(this._timeout)}["abort","flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(r){Ti.prototype[r]=function(e,t){return this._currentRequest[r](e,t)}});["aborted","connection","socket"].forEach(function(r){Object.defineProperty(Ti.prototype,r,{get:function(){return this._currentRequest[r]}})});Ti.prototype._sanitizeOptions=function(r){if(r.headers||(r.headers={}),r.host&&(r.hostname||(r.hostname=r.host),delete r.host),!r.pathname&&r.path){var e=r.path.indexOf("?");e<0?r.pathname=r.path:(r.pathname=r.path.substring(0,e),r.search=r.path.substring(e))}};Ti.prototype._performRequest=function(){var r=this._options.protocol,e=this._options.nativeProtocols[r];if(!e){this.emit("error",new TypeError("Unsupported protocol "+r));return}if(this._options.agents){var t=r.substr(0,r.length-1);this._options.agent=this._options.agents[t]}var i=this._currentRequest=e.request(this._options,this._onNativeResponse);this._currentUrl=eu.format(this._options),i._redirectable=this;for(var n in q0)n&&i.on(n,q0[n]);if(this._isRedirect){var o=0,s=this,a=this._requestBodyBuffers;(function l(u){if(i===s._currentRequest)if(u)s.emit("error",u);else if(o=300&&e<400){if(this._currentRequest.removeAllListeners(),this._currentRequest.on("error",qhe),this._currentRequest.abort(),r.destroy(),++this._redirectCount>this._options.maxRedirects){this.emit("error",new Lhe);return}((e===301||e===302)&&this._options.method==="POST"||e===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],$0(/^content-/i,this._options.headers));var i=$0(/^host$/i,this._options.headers)||eu.parse(this._currentUrl).hostname,n=eu.resolve(this._currentUrl,t);MU("redirecting to",n),this._isRedirect=!0;var o=eu.parse(n);if(Object.assign(this._options,o),o.hostname!==i&&$0(/^authorization$/i,this._options.headers),typeof this._options.beforeRedirect=="function"){var s={headers:r.headers};try{this._options.beforeRedirect.call(null,this._options,s)}catch(l){this.emit("error",l);return}this._sanitizeOptions(this._options)}try{this._performRequest()}catch(l){var a=new Ohe("Redirected request failed: "+l.message);a.cause=l,this.emit("error",a)}}else r.responseUrl=this._currentUrl,r.redirects=this._redirects,this.emit("response",r),this._requestBodyBuffers=[]};function BU(r){var e={maxRedirects:21,maxBodyLength:10*1024*1024},t={};return Object.keys(r).forEach(function(i){var n=i+":",o=t[n]=r[i],s=e[i]=Object.create(o);s.request=function(a,l,u){if(typeof a=="string"){var c=a;try{a=$U(new N0(c))}catch(f){a=eu.parse(c)}}else N0&&a instanceof N0?a=$U(a):(u=l,l=a,a={protocol:n});return typeof l=="function"&&(u=l,l=null),l=Object.assign({maxRedirects:e.maxRedirects,maxBodyLength:e.maxBodyLength},a,l),l.nativeProtocols=t,Ahe.equal(l.protocol,n,"protocol mismatch"),MU("options",l),new Ti(l,u)},s.get=function(a,l,u){var c=s.request(a,l,u);return c.end(),c}}),e}function qhe(){}function $U(r){var e={protocol:r.protocol,hostname:r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,hash:r.hash,search:r.search,pathname:r.pathname,path:r.pathname+r.search,href:r.href};return r.port!==""&&(e.port=Number(r.port)),e}function $0(r,e){var t;for(var i in e)r.test(i)&&(t=e[i],delete e[i]);return t}function gg(r,e){function t(i){Error.captureStackTrace(this,this.constructor),this.message=i||e}return t.prototype=new Error,t.prototype.constructor=t,t.prototype.name="Error ["+r+"]",t.prototype.code=r,t}M0.exports=BU({http:Ihe,https:Fhe});M0.exports.wrap=BU});var tu=g((HAe,jU)=>{"use strict";var UU=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"]]),WAe=jU.exports=r=>r?Object.keys(r).map(e=>[UU.has(e)?UU.get(e):e,r[e]]).reduce((e,t)=>(e[t[0]]=t[1],e),Object.create(null)):{}});var HU=g((zAe,WU)=>{"use strict";WU.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var vg=g((GAe,zU)=>{"use strict";zU.exports=Ie;Ie.Node=na;Ie.create=Ie;function Ie(r){var e=this;if(e instanceof Ie||(e=new Ie),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};Ie.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};Ie.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};Ie.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};Ie.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new Ie;if(ethis.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&ithis.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};Ie.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i{"use strict";var Uhe=require("events"),VU=require("stream"),pp=vg(),KU=require("string_decoder").StringDecoder,Jn=Symbol("EOF"),dp=Symbol("maybeEmitEnd"),zo=Symbol("emittedEnd"),yg=Symbol("emittingEnd"),bg=Symbol("closed"),JU=Symbol("read"),YU=Symbol("flush"),XU=Symbol("flushChunk"),Or=Symbol("encoding"),Yn=Symbol("decoder"),wg=Symbol("flowing"),hp=Symbol("paused"),mp=Symbol("resume"),Lr=Symbol("bufferLength"),ZU=Symbol("bufferPush"),j0=Symbol("bufferShift"),lr=Symbol("objectMode"),ur=Symbol("destroyed"),QU=global._MP_NO_ITERATOR_SYMBOLS_!=="1",Whe=QU&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),Hhe=QU&&Symbol.iterator||Symbol("iterator not implemented"),e6=r=>r==="end"||r==="finish"||r==="prefinish",zhe=r=>r instanceof ArrayBuffer||typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,Ghe=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r);GU.exports=class t6 extends VU{constructor(e){super();this[wg]=!1,this[hp]=!1,this.pipes=new pp,this.buffer=new pp,this[lr]=e&&e.objectMode||!1,this[lr]?this[Or]=null:this[Or]=e&&e.encoding||null,this[Or]==="buffer"&&(this[Or]=null),this[Yn]=this[Or]?new KU(this[Or]):null,this[Jn]=!1,this[zo]=!1,this[yg]=!1,this[bg]=!1,this.writable=!0,this.readable=!0,this[Lr]=0,this[ur]=!1}get bufferLength(){return this[Lr]}get encoding(){return this[Or]}set encoding(e){if(this[lr])throw new Error("cannot set encoding in objectMode");if(this[Or]&&e!==this[Or]&&(this[Yn]&&this[Yn].lastNeed||this[Lr]))throw new Error("cannot change encoding");this[Or]!==e&&(this[Yn]=e?new KU(e):null,this.buffer.length&&(this.buffer=this.buffer.map(t=>this[Yn].write(t)))),this[Or]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[lr]}set objectMode(e){this[lr]=this[lr]||!!e}write(e,t,i){if(this[Jn])throw new Error("write after end");if(this[ur])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8"),!this[lr]&&!Buffer.isBuffer(e)&&(Ghe(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):zhe(e)?e=Buffer.from(e):typeof e!="string"&&(this.objectMode=!0)),!this.objectMode&&!e.length){let n=this.flowing;return this[Lr]!==0&&this.emit("readable"),i&&i(),n}typeof e=="string"&&!this[lr]&&!(t===this[Or]&&!this[Yn].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Or]&&(e=this[Yn].write(e));try{return this.flowing?(this.emit("data",e),this.flowing):(this[ZU](e),!1)}finally{this[Lr]!==0&&this.emit("readable"),i&&i()}}read(e){if(this[ur])return null;try{return this[Lr]===0||e===0||e>this[Lr]?null:(this[lr]&&(e=null),this.buffer.length>1&&!this[lr]&&(this.encoding?this.buffer=new pp([Array.from(this.buffer).join("")]):this.buffer=new pp([Buffer.concat(Array.from(this.buffer),this[Lr])])),this[JU](e||null,this.buffer.head.value))}finally{this[dp]()}}[JU](e,t){return e===t.length||e===null?this[j0]():(this.buffer.head.value=t.slice(e),t=t.slice(0,e),this[Lr]-=e),this.emit("data",t),!this.buffer.length&&!this[Jn]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=null),typeof t=="function"&&(i=t,t="utf8"),e&&this.write(e,t),i&&this.once("end",i),this[Jn]=!0,this.writable=!1,(this.flowing||!this[hp])&&this[dp](),this}[mp](){this[ur]||(this[hp]=!1,this[wg]=!0,this.emit("resume"),this.buffer.length?this[YU]():this[Jn]?this[dp]():this.emit("drain"))}resume(){return this[mp]()}pause(){this[wg]=!1,this[hp]=!0}get destroyed(){return this[ur]}get flowing(){return this[wg]}get paused(){return this[hp]}[ZU](e){return this[lr]?this[Lr]+=1:this[Lr]+=e.length,this.buffer.push(e)}[j0](){return this.buffer.length&&(this[lr]?this[Lr]-=1:this[Lr]-=this.buffer.head.value.length),this.buffer.shift()}[YU](){do;while(this[XU](this[j0]()));!this.buffer.length&&!this[Jn]&&this.emit("drain")}[XU](e){return e?(this.emit("data",e),this.flowing):!1}pipe(e,t){if(this[ur])return;let i=this[zo];t=t||{},e===process.stdout||e===process.stderr?t.end=!1:t.end=t.end!==!1;let n={dest:e,opts:t,ondrain:o=>this[mp]()};return this.pipes.push(n),e.on("drain",n.ondrain),this[mp](),i&&n.opts.end&&n.dest.end(),e}addListener(e,t){return this.on(e,t)}on(e,t){try{return super.on(e,t)}finally{e==="data"&&!this.pipes.length&&!this.flowing?this[mp]():e6(e)&&this[zo]&&(super.emit(e),this.removeAllListeners(e))}}get emittedEnd(){return this[zo]}[dp](){!this[yg]&&!this[zo]&&!this[ur]&&this.buffer.length===0&&this[Jn]&&(this[yg]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[bg]&&this.emit("close"),this[yg]=!1)}emit(e,t){if(e!=="error"&&e!=="close"&&e!==ur&&this[ur])return;if(e==="data"){if(!t)return;this.pipes.length&&this.pipes.forEach(n=>n.dest.write(t)===!1&&this.pause())}else if(e==="end"){if(this[zo]===!0)return;this[zo]=!0,this.readable=!1,this[Yn]&&(t=this[Yn].end(),t&&(this.pipes.forEach(n=>n.dest.write(t)),super.emit("data",t))),this.pipes.forEach(n=>{n.dest.removeListener("drain",n.ondrain),n.opts.end&&n.dest.end()})}else if(e==="close"&&(this[bg]=!0,!this[zo]&&!this[ur]))return;let i=new Array(arguments.length);if(i[0]=e,i[1]=t,arguments.length>2)for(let n=2;n{e.push(i),this[lr]||(e.dataLength+=i.length)}),t.then(()=>e)}concat(){return this[lr]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then(e=>this[lr]?Promise.reject(new Error("cannot concat in objectMode")):this[Or]?e.join(""):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(ur,()=>t(new Error("stream destroyed"))),this.on("end",()=>e()),this.on("error",i=>t(i))})}[Whe](){return{next:()=>{let t=this.read();if(t!==null)return Promise.resolve({done:!1,value:t});if(this[Jn])return Promise.resolve({done:!0});let i=null,n=null,o=u=>{this.removeListener("data",s),this.removeListener("end",a),n(u)},s=u=>{this.removeListener("error",o),this.removeListener("end",a),this.pause(),i({value:u,done:!!this[Jn]})},a=()=>{this.removeListener("error",o),this.removeListener("data",s),i({done:!0})},l=()=>o(new Error("stream destroyed"));return new Promise((u,c)=>{n=c,i=u,this.once(ur,l),this.once("error",o),this.once("end",a),this.once("data",s)})}}}[Hhe](){return{next:()=>{let t=this.read();return{value:t,done:t===null}}}}destroy(e){return this[ur]?(e?this.emit("error",e):this.emit(ur),this):(this[ur]=!0,this.buffer=new pp,this[Lr]=0,typeof this.close=="function"&&!this[bg]&&this.close(),e?this.emit("error",e):this.emit(ur),this)}static isStream(e){return!!e&&(e instanceof t6||e instanceof VU||e instanceof Uhe&&(typeof e.pipe=="function"||typeof e.write=="function"&&typeof e.end=="function"))}}});var i6=g((KAe,r6)=>{var Vhe=require("zlib").constants||{ZLIB_VERNUM:4736};r6.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:Infinity,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Vhe))});var Y0=g(ti=>{"use strict";var U0=require("assert"),Go=require("buffer").Buffer,n6=require("zlib"),oa=ti.constants=i6(),Khe=ru(),o6=Go.concat,sa=Symbol("_superWrite"),gp=class extends Error{constructor(e){super("zlib: "+e.message);this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,this.constructor)}get name(){return"ZlibError"}},Jhe=Symbol("opts"),vp=Symbol("flushFlag"),s6=Symbol("finishFlushFlag"),W0=Symbol("fullFlushFlag"),Xe=Symbol("handle"),xg=Symbol("onError"),iu=Symbol("sawError"),H0=Symbol("level"),z0=Symbol("strategy"),G0=Symbol("ended"),JAe=Symbol("_defaultFullFlush"),V0=class extends Khe{constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");super(e);this[iu]=!1,this[G0]=!1,this[Jhe]=e,this[vp]=e.flush,this[s6]=e.finishFlush;try{this[Xe]=new n6[t](e)}catch(i){throw new gp(i)}this[xg]=i=>{this[iu]||(this[iu]=!0,this.close(),this.emit("error",i))},this[Xe].on("error",i=>this[xg](new gp(i))),this.once("end",()=>this.close)}close(){this[Xe]&&(this[Xe].close(),this[Xe]=null,this.emit("close"))}reset(){if(!this[iu])return U0(this[Xe],"zlib binding closed"),this[Xe].reset()}flush(e){this.ended||(typeof e!="number"&&(e=this[W0]),this.write(Object.assign(Go.alloc(0),{[vp]:e})))}end(e,t,i){return e&&this.write(e,t),this.flush(this[s6]),this[G0]=!0,super.end(null,null,i)}get ended(){return this[G0]}write(e,t,i){if(typeof t=="function"&&(i=t,t="utf8"),typeof e=="string"&&(e=Go.from(e,t)),this[iu])return;U0(this[Xe],"zlib binding closed");let n=this[Xe]._handle,o=n.close;n.close=()=>{};let s=this[Xe].close;this[Xe].close=()=>{},Go.concat=u=>u;let a;try{let u=typeof e[vp]=="number"?e[vp]:this[vp];a=this[Xe]._processChunk(e,u),Go.concat=o6}catch(u){Go.concat=o6,this[xg](new gp(u))}finally{this[Xe]&&(this[Xe]._handle=n,n.close=o,this[Xe].close=s,this[Xe].removeAllListeners("error"))}this[Xe]&&this[Xe].on("error",u=>this[xg](new gp(u)));let l;if(a)if(Array.isArray(a)&&a.length>0){l=this[sa](Go.from(a[0]));for(let u=1;u{this.flush(n),o()};try{this[Xe].params(e,t)}finally{this[Xe].flush=i}this[Xe]&&(this[H0]=e,this[z0]=t)}}}},a6=class extends Vo{constructor(e){super(e,"Deflate")}},l6=class extends Vo{constructor(e){super(e,"Inflate")}},K0=Symbol("_portable"),u6=class extends Vo{constructor(e){super(e,"Gzip");this[K0]=e&&!!e.portable}[sa](e){return this[K0]?(this[K0]=!1,e[9]=255,super[sa](e)):super[sa](e)}},c6=class extends Vo{constructor(e){super(e,"Gunzip")}},f6=class extends Vo{constructor(e){super(e,"DeflateRaw")}},p6=class extends Vo{constructor(e){super(e,"InflateRaw")}},d6=class extends Vo{constructor(e){super(e,"Unzip")}},J0=class extends V0{constructor(e,t){e=e||{},e.flush=e.flush||oa.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||oa.BROTLI_OPERATION_FINISH,super(e,t),this[W0]=oa.BROTLI_OPERATION_FLUSH}},h6=class extends J0{constructor(e){super(e,"BrotliCompress")}},m6=class extends J0{constructor(e){super(e,"BrotliDecompress")}};ti.Deflate=a6;ti.Inflate=l6;ti.Gzip=u6;ti.Gunzip=c6;ti.DeflateRaw=f6;ti.InflateRaw=p6;ti.Unzip=d6;typeof n6.BrotliCompress=="function"?(ti.BrotliCompress=h6,ti.BrotliDecompress=m6):ti.BrotliCompress=ti.BrotliDecompress=class{constructor(){throw new Error("Brotli is not supported in this version of Node.js")}}});var yp=g(Dg=>{"use strict";Dg.name=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Dg.code=new Map(Array.from(Dg.name).map(r=>[r[1],r[0]]))});var bp=g((eOe,g6)=>{"use strict";var ZAe=yp(),Yhe=ru(),X0=Symbol("slurp");g6.exports=class extends Yhe{constructor(e,t,i){super();switch(this.pause(),this.extended=t,this.globalExtended=i,this.header=e,this.startBlockSize=512*Math.ceil(e.size/512),this.blockRemain=this.startBlockSize,this.remain=e.size,this.type=e.type,this.meta=!1,this.ignore=!1,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}this.path=e.path,this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=e.size,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath,this.uname=e.uname,this.gname=e.gname,t&&this[X0](t),i&&this[X0](i,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,n=this.blockRemain;return this.remain=Math.max(0,i-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:i>=t?super.write(e):super.write(e.slice(0,i))}[X0](e,t){for(let i in e)e[i]!==null&&e[i]!==void 0&&!(t&&i==="path")&&(this[i]=e[i])}}});var b6=g(Z0=>{"use strict";var tOe=Z0.encode=(r,e)=>{if(Number.isSafeInteger(r))r<0?Zhe(r,e):Xhe(r,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Xhe=(r,e)=>{e[0]=128;for(var t=e.length;t>1;t--)e[t-1]=r&255,r=Math.floor(r/256)},Zhe=(r,e)=>{e[0]=255;var t=!1;r=r*-1;for(var i=e.length;i>1;i--){var n=r&255;r=Math.floor(r/256),t?e[i-1]=v6(n):n===0?e[i-1]=0:(t=!0,e[i-1]=y6(n))}},rOe=Z0.parse=r=>{var e=r[r.length-1],t=r[0],i;if(t===128)i=eme(r.slice(1,r.length));else if(t===255)i=Qhe(r);else throw Error("invalid base256 encoding");if(!Number.isSafeInteger(i))throw Error("parsed number outside of javascript safe integer range");return i},Qhe=r=>{for(var e=r.length,t=0,i=!1,n=e-1;n>-1;n--){var o=r[n],s;i?s=v6(o):o===0?s=o:(i=!0,s=y6(o)),s!==0&&(t-=s*Math.pow(256,e-n-1))}return t},eme=r=>{for(var e=r.length,t=0,i=e-1;i>-1;i--){var n=r[i];n!==0&&(t+=n*Math.pow(256,e-i-1))}return t},v6=r=>(255^r)&255,y6=r=>(255^r)+1&255});var ou=g((nOe,w6)=>{"use strict";var Q0=yp(),nu=require("path").posix,x6=b6(),eS=Symbol("slurp"),ri=Symbol("type"),D6=class{constructor(e,t,i,n){this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[ri]="0",this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer(e)?this.decode(e,t||0,i,n):e&&this.set(e)}decode(e,t,i,n){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");if(this.path=aa(e,t,100),this.mode=Ko(e,t+100,8),this.uid=Ko(e,t+108,8),this.gid=Ko(e,t+116,8),this.size=Ko(e,t+124,12),this.mtime=tS(e,t+136,12),this.cksum=Ko(e,t+148,12),this[eS](i),this[eS](n,!0),this[ri]=aa(e,t+156,1),this[ri]===""&&(this[ri]="0"),this[ri]==="0"&&this.path.substr(-1)==="/"&&(this[ri]="5"),this[ri]==="5"&&(this.size=0),this.linkpath=aa(e,t+157,100),e.slice(t+257,t+265).toString()==="ustar\x0000")if(this.uname=aa(e,t+265,32),this.gname=aa(e,t+297,32),this.devmaj=Ko(e,t+329,8),this.devmin=Ko(e,t+337,8),e[t+475]!==0){let s=aa(e,t+345,155);this.path=s+"/"+this.path}else{let s=aa(e,t+345,130);s&&(this.path=s+"/"+this.path),this.atime=tS(e,t+476,12),this.ctime=tS(e,t+488,12)}let o=8*32;for(let s=t;s=t+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,n=tme(this.path||"",i),o=n[0],s=n[1];this.needPax=n[2],this.needPax=la(e,t,100,o)||this.needPax,this.needPax=Jo(e,t+100,8,this.mode)||this.needPax,this.needPax=Jo(e,t+108,8,this.uid)||this.needPax,this.needPax=Jo(e,t+116,8,this.gid)||this.needPax,this.needPax=Jo(e,t+124,12,this.size)||this.needPax,this.needPax=rS(e,t+136,12,this.mtime)||this.needPax,e[t+156]=this[ri].charCodeAt(0),this.needPax=la(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=la(e,t+265,32,this.uname)||this.needPax,this.needPax=la(e,t+297,32,this.gname)||this.needPax,this.needPax=Jo(e,t+329,8,this.devmaj)||this.needPax,this.needPax=Jo(e,t+337,8,this.devmin)||this.needPax,this.needPax=la(e,t+345,i,s)||this.needPax,e[t+475]!==0?this.needPax=la(e,t+345,155,s)||this.needPax:(this.needPax=la(e,t+345,130,s)||this.needPax,this.needPax=rS(e,t+476,12,this.atime)||this.needPax,this.needPax=rS(e,t+488,12,this.ctime)||this.needPax);let a=8*32;for(let l=t;l{let t=100,i=r,n="",o,s=nu.parse(r).root||".";if(Buffer.byteLength(i)t&&Buffer.byteLength(n)<=e?o=[i.substr(0,t-1),n,!0]:(i=nu.join(nu.basename(n),i),n=nu.dirname(n));while(n!==s&&!o);o||(o=[r.substr(0,t-1),"",!0])}return o},aa=(r,e,t)=>r.slice(e,e+t).toString("utf8").replace(/\0.*/,""),tS=(r,e,t)=>rme(Ko(r,e,t)),rme=r=>r===null?null:new Date(r*1e3),Ko=(r,e,t)=>r[e]&128?x6.parse(r.slice(e,e+t)):ime(r,e,t),nme=r=>isNaN(r)?null:r,ime=(r,e,t)=>nme(parseInt(r.slice(e,e+t).toString("utf8").replace(/\0.*$/,"").trim(),8)),ome={12:8589934591,8:2097151},Jo=(r,e,t,i)=>i===null?!1:i>ome[t]||i<0?(x6.encode(i,r.slice(e,e+t)),!0):(sme(r,e,t,i),!1),sme=(r,e,t,i)=>r.write(ame(i,t),e,t,"ascii"),ame=(r,e)=>lme(Math.floor(r).toString(8),e),lme=(r,e)=>(r.length===e-1?r:new Array(e-r.length-1).join("0")+r+" ")+"\0",rS=(r,e,t,i)=>i===null?!1:Jo(r,e,t,i.getTime()/1e3),ume=new Array(156).join("\0"),la=(r,e,t,i)=>i===null?!1:(r.write(i+ume,e,t,"utf8"),i.length!==Buffer.byteLength(i)||i.length>t);w6.exports=D6});var Eg=g((oOe,S6)=>{"use strict";var cme=ou(),fme=require("path"),Sg=class{constructor(e,t){this.atime=e.atime||null,this.charset=e.charset||null,this.comment=e.comment||null,this.ctime=e.ctime||null,this.gid=e.gid||null,this.gname=e.gname||null,this.linkpath=e.linkpath||null,this.mtime=e.mtime||null,this.path=e.path||null,this.size=e.size||null,this.uid=e.uid||null,this.uname=e.uname||null,this.dev=e.dev||null,this.ino=e.ino||null,this.nlink=e.nlink||null,this.global=t||!1}encode(){let e=this.encodeBody();if(e==="")return null;let t=Buffer.byteLength(e),i=512*Math.ceil(1+t/512),n=Buffer.allocUnsafe(i);for(let o=0;o<512;o++)n[o]=0;new cme({path:("PaxHeader/"+fme.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:t,mtime:this.mtime||null,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(n),n.write(e,512,t,"utf8");for(let o=t+512;o=Math.pow(10,o)&&(o+=1),o+n+i}};Sg.parse=(r,e,t)=>new Sg(pme(dme(r),e),t);var pme=(r,e)=>e?Object.keys(r).reduce((t,i)=>(t[i]=r[i],t),e):r,dme=r=>r.replace(/\n$/,"").split(` +`).reduce(hme,Object.create(null)),hme=(r,e)=>{let t=parseInt(e,10);if(t!==Buffer.byteLength(e)+1)return r;e=e.substr((t+" ").length);let i=e.split("="),n=i.shift().replace(/^SCHILY\.(dev|ino|nlink)/,"$1");if(!n)return r;let o=i.join("=");return r[n]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(n)?new Date(o*1e3):/^[0-9]+$/.test(o)?+o:o,r};S6.exports=Sg});var Cg=g((sOe,E6)=>{"use strict";E6.exports=r=>class extends r{warn(e,t,i={}){this.file&&(i.file=this.file),this.cwd&&(i.cwd=this.cwd),i.code=t instanceof Error&&t.code||e,i.tarCode=e,!this.strict&&i.recoverable!==!1?(t instanceof Error&&(i=Object.assign(t,i),t=t.message),this.emit("warn",i.tarCode,t,i)):t instanceof Error?this.emit("error",Object.assign(t,i)):this.emit("error",Object.assign(new Error(`${e}: ${t}`),i))}}});var nS=g((aOe,C6)=>{"use strict";var _g=["|","<",">","?",":"],iS=_g.map(r=>String.fromCharCode(61440+r.charCodeAt(0))),mme=new Map(_g.map((r,e)=>[r,iS[e]])),gme=new Map(iS.map((r,e)=>[r,_g[e]]));C6.exports={encode:r=>_g.reduce((e,t)=>e.split(t).join(mme.get(t)),r),decode:r=>iS.reduce((e,t)=>e.split(t).join(gme.get(t)),r)}});var P6=g((lOe,_6)=>{"use strict";_6.exports=(r,e,t)=>(r&=4095,t&&(r=(r|384)&~18),e&&(r&256&&(r|=64),r&32&&(r|=8),r&4&&(r|=1)),r)});var fS=g((dOe,T6)=>{"use strict";var R6=ru(),k6=Eg(),I6=ou(),uOe=bp(),bn=require("fs"),su=require("path"),cOe=yp(),vme=16*1024*1024,F6=Symbol("process"),A6=Symbol("file"),O6=Symbol("directory"),oS=Symbol("symlink"),L6=Symbol("hardlink"),wp=Symbol("header"),Pg=Symbol("read"),sS=Symbol("lstat"),Tg=Symbol("onlstat"),aS=Symbol("onread"),lS=Symbol("onreadlink"),uS=Symbol("openfile"),cS=Symbol("onopenfile"),ua=Symbol("close"),Rg=Symbol("mode"),M6=Cg(),yme=nS(),N6=P6(),kg=M6(class extends R6{constructor(e,t){if(t=t||{},super(t),typeof e!="string")throw new TypeError("path is required");this.path=e,this.portable=!!t.portable,this.myuid=process.getuid&&process.getuid(),this.myuser=process.env.USER||"",this.maxReadSize=t.maxReadSize||vme,this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.preservePaths=!!t.preservePaths,this.cwd=t.cwd||process.cwd(),this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.mtime=t.mtime||null,typeof t.onwarn=="function"&&this.on("warn",t.onwarn);let i=!1;if(!this.preservePaths&&su.win32.isAbsolute(e)){let n=su.win32.parse(e);this.path=e.substr(n.root.length),i=n.root}this.win32=!!t.win32||process.platform==="win32",this.win32&&(this.path=yme.decode(this.path.replace(/\\/g,"/")),e=e.replace(/\\/g,"/")),this.absolute=t.absolute||su.resolve(this.cwd,e),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.statCache.has(this.absolute)?this[Tg](this.statCache.get(this.absolute)):this[sS]()}[sS](){bn.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Tg](t)})}[Tg](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=bme(e),this.emit("stat",e),this[F6]()}[F6](){switch(this.type){case"File":return this[A6]();case"Directory":return this[O6]();case"SymbolicLink":return this[oS]();default:return this.end()}}[Rg](e){return N6(e,this.type==="Directory",this.portable)}[wp](){this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.header=new I6({path:this.path,linkpath:this.linkpath,mode:this[Rg](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax&&this.write(new k6({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this.path,linkpath:this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode()),this.write(this.header.block)}[O6](){this.path.substr(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wp](),this.end()}[oS](){bn.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[lS](t)})}[lS](e){this.linkpath=e.replace(/\\/g,"/"),this[wp](),this.end()}[L6](e){this.type="Link",this.linkpath=su.relative(this.cwd,e).replace(/\\/g,"/"),this.stat.size=0,this[wp](),this.end()}[A6](){if(this.stat.nlink>1){let e=this.stat.dev+":"+this.stat.ino;if(this.linkCache.has(e)){let t=this.linkCache.get(e);if(t.indexOf(this.cwd)===0)return this[L6](t)}this.linkCache.set(e,this.absolute)}if(this[wp](),this.stat.size===0)return this.end();this[uS]()}[uS](){bn.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[cS](t)})}[cS](e){let t=512*Math.ceil(this.stat.size/512),i=Math.min(t,this.maxReadSize),n=Buffer.allocUnsafe(i);this[Pg](e,n,0,n.length,0,this.stat.size,t)}[Pg](e,t,i,n,o,s,a){bn.read(e,t,i,n,o,(l,u)=>{if(l)return this[ua](e,()=>this.emit("error",l));this[aS](e,t,i,n,o,s,a,u)})}[ua](e,t){bn.close(e,t)}[aS](e,t,i,n,o,s,a,l){if(l<=0&&s>0){let c=new Error("encountered unexpected EOF");return c.path=this.absolute,c.syscall="read",c.code="EOF",this[ua](e,()=>this.emit("error",c))}if(l>s){let c=new Error("did not encounter expected EOF");return c.path=this.absolute,c.syscall="read",c.code="EOF",this[ua](e,()=>this.emit("error",c))}if(l===s)for(let c=l;cc?this.emit("error",c):this.end());i>=n&&(t=Buffer.allocUnsafe(n),i=0),n=t.length-i,this[Pg](e,t,i,n,o,s,a)}}),q6=class extends kg{constructor(e,t){super(e,t)}[sS](){this[Tg](bn.lstatSync(this.absolute))}[oS](){this[lS](bn.readlinkSync(this.absolute))}[uS](){this[cS](bn.openSync(this.absolute,"r"))}[Pg](e,t,i,n,o,s,a){let l=!0;try{let u=bn.readSync(e,t,i,n,o);this[aS](e,t,i,n,o,s,a,u),l=!1}finally{if(l)try{this[ua](e,()=>{})}catch(u){}}}[ua](e,t){bn.closeSync(e),t()}},wme=M6(class extends R6{constructor(e,t){t=t||{},super(t),this.preservePaths=!!t.preservePaths,this.portable=!!t.portable,this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.readEntry=e,this.type=e.type,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.path=e.path,this.mode=this[Rg](e.mode),this.uid=this.portable?null:e.uid,this.gid=this.portable?null:e.gid,this.uname=this.portable?null:e.uname,this.gname=this.portable?null:e.gname,this.size=e.size,this.mtime=this.noMtime?null:t.mtime||e.mtime,this.atime=this.portable?null:e.atime,this.ctime=this.portable?null:e.ctime,this.linkpath=e.linkpath,typeof t.onwarn=="function"&&this.on("warn",t.onwarn);let i=!1;if(su.isAbsolute(this.path)&&!this.preservePaths){let n=su.parse(this.path);i=n.root,this.path=this.path.substr(n.root.length)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.header=new I6({path:this.path,linkpath:this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new k6({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this.path,linkpath:this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode()),super.write(this.header.block),e.pipe(this)}[Rg](e){return N6(e,this.type==="Directory",this.portable)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=t,super.write(e)}end(){return this.blockRemain&&this.write(Buffer.alloc(this.blockRemain)),super.end()}});kg.Sync=q6;kg.Tar=wme;var bme=r=>r.isFile()?"File":r.isDirectory()?"Directory":r.isSymbolicLink()?"SymbolicLink":"Unsupported";T6.exports=kg});var qg=g((mOe,$6)=>{"use strict";var pS=class{constructor(e,t){this.path=e||"./",this.absolute=t,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}},xme=ru(),Dme=Y0(),Sme=bp(),dS=fS(),Eme=dS.Sync,Cme=dS.Tar,_me=vg(),B6=Buffer.alloc(1024),Ig=Symbol("onStat"),Fg=Symbol("ended"),wn=Symbol("queue"),au=Symbol("current"),ca=Symbol("process"),Ag=Symbol("processing"),j6=Symbol("processJob"),xn=Symbol("jobs"),hS=Symbol("jobDone"),Og=Symbol("addFSEntry"),U6=Symbol("addTarEntry"),mS=Symbol("stat"),gS=Symbol("readdir"),Lg=Symbol("onreaddir"),Mg=Symbol("pipe"),W6=Symbol("entry"),vS=Symbol("entryOpt"),yS=Symbol("writeEntryClass"),H6=Symbol("write"),bS=Symbol("ondrain"),Ng=require("fs"),z6=require("path"),Pme=Cg(),wS=Pme(class extends xme{constructor(e){super(e);e=e||Object.create(null),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=(e.prefix||"").replace(/(\\|\/)+$/,""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this[yS]=dS,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,this.zip=null,e.gzip?(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new Dme.Gzip(e.gzip),this.zip.on("data",t=>super.write(t)),this.zip.on("end",t=>super.end()),this.zip.on("drain",t=>this[bS]()),this.on("resume",t=>this.zip.resume())):this.on("drain",this[bS]),this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,this.mtime=e.mtime||null,this.filter=typeof e.filter=="function"?e.filter:t=>!0,this[wn]=new _me,this[xn]=0,this.jobs=+e.jobs||4,this[Ag]=!1,this[Fg]=!1}[H6](e){return super.write(e)}add(e){return this.write(e),this}end(e){return e&&this.write(e),this[Fg]=!0,this[ca](),this}write(e){if(this[Fg])throw new Error("write after end");return e instanceof Sme?this[U6](e):this[Og](e),this.flowing}[U6](e){let t=z6.resolve(this.cwd,e.path);if(this.prefix&&(e.path=this.prefix+"/"+e.path.replace(/^\.(\/+|$)/,"")),!this.filter(e.path,e))e.resume();else{let i=new pS(e.path,t,!1);i.entry=new Cme(e,this[vS](i)),i.entry.on("end",n=>this[hS](i)),this[xn]+=1,this[wn].push(i)}this[ca]()}[Og](e){let t=z6.resolve(this.cwd,e);this.prefix&&(e=this.prefix+"/"+e.replace(/^\.(\/+|$)/,"")),this[wn].push(new pS(e,t)),this[ca]()}[mS](e){e.pending=!0,this[xn]+=1;let t=this.follow?"stat":"lstat";Ng[t](e.absolute,(i,n)=>{e.pending=!1,this[xn]-=1,i?this.emit("error",i):this[Ig](e,n)})}[Ig](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)||(e.ignore=!0),this[ca]()}[gS](e){e.pending=!0,this[xn]+=1,Ng.readdir(e.absolute,(t,i)=>{if(e.pending=!1,this[xn]-=1,t)return this.emit("error",t);this[Lg](e,i)})}[Lg](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[ca]()}[ca](){if(!this[Ag]){this[Ag]=!0;for(let e=this[wn].head;e!==null&&this[xn]this.warn(t,i,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime}}[W6](e){this[xn]+=1;try{return new this[yS](e.path,this[vS](e)).on("end",()=>this[hS](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[bS](){this[au]&&this[au].entry&&this[au].entry.resume()}[Mg](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let o=this.prefix?e.path.slice(this.prefix.length+1)||"./":e.path,s=o==="./"?"":o.replace(/\/*$/,"/");this[Og](s+n)});let t=e.entry,i=this.zip;i?t.on("data",n=>{i.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}}),G6=class extends wS{constructor(e){super(e);this[yS]=Eme}pause(){}resume(){}[mS](e){let t=this.follow?"statSync":"lstatSync";this[Ig](e,Ng[t](e.absolute))}[gS](e,t){this[Lg](e,Ng.readdirSync(e.absolute))}[Mg](e){let t=e.entry,i=this.zip;e.readdir&&e.readdir.forEach(n=>{let o=this.prefix?e.path.slice(this.prefix.length+1)||"./":e.path,s=o==="./"?"":o.replace(/\/*$/,"/");this[Og](s+n)}),i?t.on("data",n=>{i.write(n)}):t.on("data",n=>{super[H6](n)})}};wS.Sync=G6;$6.exports=wS});var mu=g(xp=>{"use strict";var Tme=ru(),Rme=require("events").EventEmitter,Mr=require("fs"),xS=Mr.writev;if(!xS){let r=process.binding("fs"),e=r.FSReqWrap||r.FSReqCallback;xS=(t,i,n,o)=>{let s=(l,u)=>o(l,u,i),a=new e;a.oncomplete=s,r.writeBuffers(t,i,n,a)}}var lu=Symbol("_autoClose"),rn=Symbol("_close"),Dp=Symbol("_ended"),ze=Symbol("_fd"),V6=Symbol("_finished"),Yo=Symbol("_flags"),DS=Symbol("_flush"),SS=Symbol("_handleChunk"),ES=Symbol("_makeBuf"),$g=Symbol("_mode"),Bg=Symbol("_needDrain"),uu=Symbol("_onerror"),cu=Symbol("_onopen"),CS=Symbol("_onread"),fu=Symbol("_onwrite"),Xo=Symbol("_open"),Xn=Symbol("_path"),fa=Symbol("_pos"),Dn=Symbol("_queue"),pu=Symbol("_read"),K6=Symbol("_readSize"),Zo=Symbol("_reading"),jg=Symbol("_remain"),J6=Symbol("_size"),Ug=Symbol("_write"),du=Symbol("_writing"),Wg=Symbol("_defaultFlag"),hu=Symbol("_errored"),_S=class extends Tme{constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[hu]=!1,this[ze]=typeof t.fd=="number"?t.fd:null,this[Xn]=e,this[K6]=t.readSize||16*1024*1024,this[Zo]=!1,this[J6]=typeof t.size=="number"?t.size:Infinity,this[jg]=this[J6],this[lu]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[ze]=="number"?this[pu]():this[Xo]()}get fd(){return this[ze]}get path(){return this[Xn]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Xo](){Mr.open(this[Xn],"r",(e,t)=>this[cu](e,t))}[cu](e,t){e?this[uu](e):(this[ze]=t,this.emit("open",t),this[pu]())}[ES](){return Buffer.allocUnsafe(Math.min(this[K6],this[jg]))}[pu](){if(!this[Zo]){this[Zo]=!0;let e=this[ES]();if(e.length===0)return process.nextTick(()=>this[CS](null,0,e));Mr.read(this[ze],e,0,e.length,null,(t,i,n)=>this[CS](t,i,n))}}[CS](e,t,i){this[Zo]=!1,e?this[uu](e):this[SS](t,i)&&this[pu]()}[rn](){if(this[lu]&&typeof this[ze]=="number"){let e=this[ze];this[ze]=null,Mr.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[uu](e){this[Zo]=!0,this[rn](),this.emit("error",e)}[SS](e,t){let i=!1;return this[jg]-=e,e>0&&(i=super.write(ethis[cu](e,t))}[cu](e,t){this[Wg]&&this[Yo]==="r+"&&e&&e.code==="ENOENT"?(this[Yo]="w",this[Xo]()):e?this[uu](e):(this[ze]=t,this.emit("open",t),this[DS]())}end(e,t){return e&&this.write(e,t),this[Dp]=!0,!this[du]&&!this[Dn].length&&typeof this[ze]=="number"&&this[fu](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[Dp]?(this.emit("error",new Error("write() after end()")),!1):this[ze]===null||this[du]||this[Dn].length?(this[Dn].push(e),this[Bg]=!0,!1):(this[du]=!0,this[Ug](e),!0)}[Ug](e){Mr.write(this[ze],e,0,e.length,this[fa],(t,i)=>this[fu](t,i))}[fu](e,t){e?this[uu](e):(this[fa]!==null&&(this[fa]+=t),this[Dn].length?this[DS]():(this[du]=!1,this[Dp]&&!this[V6]?(this[V6]=!0,this[rn](),this.emit("finish")):this[Bg]&&(this[Bg]=!1,this.emit("drain"))))}[DS](){if(this[Dn].length===0)this[Dp]&&this[fu](null,0);else if(this[Dn].length===1)this[Ug](this[Dn].pop());else{let e=this[Dn];this[Dn]=[],xS(this[ze],e,this[fa],(t,i)=>this[fu](t,i))}}[rn](){if(this[lu]&&typeof this[ze]=="number"){let e=this[ze];this[ze]=null,Mr.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},X6=class extends PS{[Xo](){let e;if(this[Wg]&&this[Yo]==="r+")try{e=Mr.openSync(this[Xn],this[Yo],this[$g])}catch(t){if(t.code==="ENOENT")return this[Yo]="w",this[Xo]();throw t}else e=Mr.openSync(this[Xn],this[Yo],this[$g]);this[cu](null,e)}[rn](){if(this[lu]&&typeof this[ze]=="number"){let e=this[ze];this[ze]=null,Mr.closeSync(e),this.emit("close")}}[Ug](e){let t=!0;try{this[fu](null,Mr.writeSync(this[ze],e,0,e.length,this[fa])),t=!1}finally{if(t)try{this[rn]()}catch(i){}}}};xp.ReadStream=_S;xp.ReadStreamSync=Y6;xp.WriteStream=PS;xp.WriteStreamSync=X6});var Cp=g((bOe,Z6)=>{"use strict";var kme=Cg(),vOe=require("path"),Ime=ou(),Fme=require("events"),Ame=vg(),Ome=1024*1024,Lme=bp(),Q6=Eg(),Mme=Y0(),TS=Buffer.from([31,139]),Ri=Symbol("state"),pa=Symbol("writeEntry"),Zn=Symbol("readEntry"),RS=Symbol("nextEntry"),e8=Symbol("processEntry"),ki=Symbol("extendedHeader"),Sp=Symbol("globalExtendedHeader"),Qo=Symbol("meta"),t8=Symbol("emitMeta"),et=Symbol("buffer"),Qn=Symbol("queue"),da=Symbol("ended"),r8=Symbol("emittedEnd"),ha=Symbol("emit"),Nr=Symbol("unzip"),Hg=Symbol("consumeChunk"),zg=Symbol("consumeChunkSub"),kS=Symbol("consumeBody"),i8=Symbol("consumeMeta"),n8=Symbol("consumeHeader"),Gg=Symbol("consuming"),IS=Symbol("bufferConcat"),FS=Symbol("maybeEnd"),Ep=Symbol("writing"),es=Symbol("aborted"),Vg=Symbol("onDone"),ma=Symbol("sawValidEntry"),Kg=Symbol("sawNullBlock"),Jg=Symbol("sawEOF"),Nme=r=>!0;Z6.exports=kme(class extends Fme{constructor(e){e=e||{},super(e),this.file=e.file||"",this[ma]=null,this.on(Vg,t=>{(this[Ri]==="begin"||this[ma]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(Vg,e.ondone):this.on(Vg,t=>{this.emit("prefinish"),this.emit("finish"),this.emit("end"),this.emit("close")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||Ome,this.filter=typeof e.filter=="function"?e.filter:Nme,this.writable=!0,this.readable=!1,this[Qn]=new Ame,this[et]=null,this[Zn]=null,this[pa]=null,this[Ri]="begin",this[Qo]="",this[ki]=null,this[Sp]=null,this[da]=!1,this[Nr]=null,this[es]=!1,this[Kg]=!1,this[Jg]=!1,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onentry=="function"&&this.on("entry",e.onentry)}[n8](e,t){this[ma]===null&&(this[ma]=!1);let i;try{i=new Ime(e,t,this[ki],this[Sp])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(i.nullBlock)this[Kg]?(this[Jg]=!0,this[Ri]==="begin"&&(this[Ri]="header"),this[ha]("eof")):(this[Kg]=!0,this[ha]("nullBlock"));else if(this[Kg]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let n=i.type;if(/^(Symbolic)?Link$/.test(n)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(n)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let o=this[pa]=new Lme(i,this[ki],this[Sp]);if(!this[ma])if(o.remain){let s=()=>{o.invalid||(this[ma]=!0)};o.on("end",s)}else this[ma]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[ha]("ignoredEntry",o),this[Ri]="ignore",o.resume()):o.size>0&&(this[Qo]="",o.on("data",s=>this[Qo]+=s),this[Ri]="meta"):(this[ki]=null,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[ha]("ignoredEntry",o),this[Ri]=o.remain?"ignore":"header",o.resume()):(o.remain?this[Ri]="body":(this[Ri]="header",o.end()),this[Zn]?this[Qn].push(o):(this[Qn].push(o),this[RS]())))}}}[e8](e){let t=!0;return e?Array.isArray(e)?this.emit.apply(this,e):(this[Zn]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",i=>this[RS]()),t=!1)):(this[Zn]=null,t=!1),t}[RS](){do;while(this[e8](this[Qn].shift()));if(!this[Qn].length){let e=this[Zn];!e||e.flowing||e.size===e.remain?this[Ep]||this.emit("drain"):e.once("drain",i=>this.emit("drain"))}}[kS](e,t){let i=this[pa],n=i.blockRemain,o=n>=e.length&&t===0?e:e.slice(t,t+n);return i.write(o),i.blockRemain||(this[Ri]="header",this[pa]=null,i.end()),o.length}[i8](e,t){let i=this[pa],n=this[kS](e,t);return this[pa]||this[t8](i),n}[ha](e,t,i){!this[Qn].length&&!this[Zn]?this.emit(e,t,i):this[Qn].push([e,t,i])}[t8](e){switch(this[ha]("meta",this[Qo]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[ki]=Q6.parse(this[Qo],this[ki],!1);break;case"GlobalExtendedHeader":this[Sp]=Q6.parse(this[Qo],this[Sp],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":this[ki]=this[ki]||Object.create(null),this[ki].path=this[Qo].replace(/\0.*/,"");break;case"NextFileHasLongLinkpath":this[ki]=this[ki]||Object.create(null),this[ki].linkpath=this[Qo].replace(/\0.*/,"");break;default:throw new Error("unknown meta: "+e.type)}}abort(e){this[es]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e){if(this[es])return;if(this[Nr]===null&&e){if(this[et]&&(e=Buffer.concat([this[et],e]),this[et]=null),e.lengththis[Hg](o)),this[Nr].on("error",o=>this.abort(o)),this[Nr].on("end",o=>{this[da]=!0,this[Hg]()}),this[Ep]=!0;let n=this[Nr][i?"end":"write"](e);return this[Ep]=!1,n}}this[Ep]=!0,this[Nr]?this[Nr].write(e):this[Hg](e),this[Ep]=!1;let t=this[Qn].length?!1:this[Zn]?this[Zn].flowing:!0;return!t&&!this[Qn].length&&this[Zn].once("drain",i=>this.emit("drain")),t}[IS](e){e&&!this[es]&&(this[et]=this[et]?Buffer.concat([this[et],e]):e)}[FS](){if(this[da]&&!this[r8]&&!this[es]&&!this[Gg]){this[r8]=!0;let e=this[pa];if(e&&e.blockRemain){let t=this[et]?this[et].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[et]&&e.write(this[et]),e.end()}this[ha](Vg)}}[Hg](e){if(this[Gg])this[IS](e);else if(!e&&!this[et])this[FS]();else{if(this[Gg]=!0,this[et]){this[IS](e);let t=this[et];this[et]=null,this[zg](t)}else this[zg](e);for(;this[et]&&this[et].length>=512&&!this[es]&&!this[Jg];){let t=this[et];this[et]=null,this[zg](t)}this[Gg]=!1}(!this[et]||this[da])&&this[FS]()}[zg](e){let t=0,i=e.length;for(;t+512<=i&&!this[es]&&!this[Jg];)switch(this[Ri]){case"begin":case"header":this[n8](e,t),t+=512;break;case"ignore":case"body":t+=this[kS](e,t);break;case"meta":t+=this[i8](e,t);break;default:throw new Error("invalid state: "+this[Ri])}t{"use strict";var qme=tu(),s8=Cp(),gu=require("fs"),$me=mu(),a8=require("path"),wOe=o8.exports=(r,e,t)=>{typeof r=="function"?(t=r,e=null,r={}):Array.isArray(r)&&(e=r,r={}),typeof e=="function"&&(t=e,e=null),e?e=Array.from(e):e=[];let i=qme(r);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return e.length&&jme(i,e),i.noResume||Bme(i),i.file&&i.sync?Ume(i):i.file?Wme(i,t):l8(i)},Bme=r=>{let e=r.onentry;r.onentry=e?t=>{e(t),t.resume()}:t=>t.resume()},jme=(r,e)=>{let t=new Map(e.map(o=>[o.replace(/\/+$/,""),!0])),i=r.filter,n=(o,s)=>{let a=s||a8.parse(o).root||".",l=o===a?!1:t.has(o)?t.get(o):n(a8.dirname(o),a);return t.set(o,l),l};r.filter=i?(o,s)=>i(o,s)&&n(o.replace(/\/+$/,"")):o=>n(o.replace(/\/+$/,""))},Ume=r=>{let e=l8(r),t=r.file,i=!0,n;try{let o=gu.statSync(t),s=r.maxReadSize||16*1024*1024;if(o.size{let t=new s8(r),i=r.maxReadSize||16*1024*1024,n=r.file,o=new Promise((s,a)=>{t.on("error",a),t.on("end",s),gu.stat(n,(l,u)=>{if(l)a(l);else{let c=new $me.ReadStream(n,{readSize:i,size:u.size});c.on("error",a),c.pipe(t)}})});return e?o.then(e,e):o},l8=r=>new s8(r)});var h8=g((EOe,u8)=>{"use strict";var Hme=tu(),Xg=qg(),DOe=require("fs"),c8=mu(),f8=Yg(),p8=require("path"),SOe=u8.exports=(r,e,t)=>{if(typeof e=="function"&&(t=e),Array.isArray(r)&&(e=r,r={}),!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");e=Array.from(e);let i=Hme(r);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return i.file&&i.sync?zme(i,e):i.file?Gme(i,e,t):i.sync?Vme(i,e):Kme(i,e)},zme=(r,e)=>{let t=new Xg.Sync(r),i=new c8.WriteStreamSync(r.file,{mode:r.mode||438});t.pipe(i),d8(t,e)},Gme=(r,e,t)=>{let i=new Xg(r),n=new c8.WriteStream(r.file,{mode:r.mode||438});i.pipe(n);let o=new Promise((s,a)=>{n.on("error",a),n.on("close",s),i.on("error",a)});return AS(i,e),t?o.then(t,t):o},d8=(r,e)=>{e.forEach(t=>{t.charAt(0)==="@"?f8({file:p8.resolve(r.cwd,t.substr(1)),sync:!0,noResume:!0,onentry:i=>r.add(i)}):r.add(t)}),r.end()},AS=(r,e)=>{for(;e.length;){let t=e.shift();if(t.charAt(0)==="@")return f8({file:p8.resolve(r.cwd,t.substr(1)),noResume:!0,onentry:i=>r.add(i)}).then(i=>AS(r,e));r.add(t)}r.end()},Vme=(r,e)=>{let t=new Xg.Sync(r);return d8(t,e),t},Kme=(r,e)=>{let t=new Xg(r);return AS(t,e),t}});var OS=g((POe,m8)=>{"use strict";var Jme=tu(),g8=qg(),COe=Cp(),Ii=require("fs"),v8=mu(),y8=Yg(),b8=require("path"),w8=ou(),_Oe=m8.exports=(r,e,t)=>{let i=Jme(r);if(!i.file)throw new TypeError("file is required");if(i.gzip)throw new TypeError("cannot append to compressed archives");if(!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");return e=Array.from(e),i.sync?Yme(i,e):Xme(i,e,t)},Yme=(r,e)=>{let t=new g8.Sync(r),i=!0,n,o;try{try{n=Ii.openSync(r.file,"r+")}catch(l){if(l.code==="ENOENT")n=Ii.openSync(r.file,"w+");else throw l}let s=Ii.fstatSync(n),a=Buffer.alloc(512);e:for(o=0;os.size)break;o+=u,r.mtimeCache&&r.mtimeCache.set(l.path,l.mtime)}i=!1,Zme(r,t,o,n,e)}finally{if(i)try{Ii.closeSync(n)}catch(s){}}},Zme=(r,e,t,i,n)=>{let o=new v8.WriteStreamSync(r.file,{fd:i,start:t});e.pipe(o),Qme(e,n)},Xme=(r,e,t)=>{e=Array.from(e);let i=new g8(r),n=(s,a,l)=>{let u=(h,m)=>{h?Ii.close(s,y=>l(h)):l(null,m)},c=0;if(a===0)return u(null,0);let f=0,p=Buffer.alloc(512),d=(h,m)=>{if(h)return u(h);if(f+=m,f<512&&m)return Ii.read(s,p,f,p.length-f,c+f,d);if(c===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(f<512)return u(null,c);let y=new w8(p);if(!y.cksumValid)return u(null,c);let v=512*Math.ceil(y.size/512);if(c+v+512>a||(c+=v+512,c>=a))return u(null,c);r.mtimeCache&&r.mtimeCache.set(y.path,y.mtime),f=0,Ii.read(s,p,0,512,c,d)};Ii.read(s,p,0,512,c,d)},o=new Promise((s,a)=>{i.on("error",a);let l="r+",u=(c,f)=>{if(c&&c.code==="ENOENT"&&l==="r+")return l="w+",Ii.open(r.file,l,u);if(c)return a(c);Ii.fstat(f,(p,d)=>{if(p)return a(p);n(f,d.size,(h,m)=>{if(h)return a(h);let y=new v8.WriteStream(r.file,{fd:f,start:m});i.pipe(y),y.on("error",a),y.on("close",s),x8(i,e)})})};Ii.open(r.file,l,u)});return t?o.then(t,t):o},Qme=(r,e)=>{e.forEach(t=>{t.charAt(0)==="@"?y8({file:b8.resolve(r.cwd,t.substr(1)),sync:!0,noResume:!0,onentry:i=>r.add(i)}):r.add(t)}),r.end()},x8=(r,e)=>{for(;e.length;){let t=e.shift();if(t.charAt(0)==="@")return y8({file:b8.resolve(r.cwd,t.substr(1)),noResume:!0,onentry:i=>r.add(i)}).then(i=>x8(r,e));r.add(t)}r.end()}});var S8=g((ROe,D8)=>{"use strict";var ege=tu(),tge=OS(),TOe=D8.exports=(r,e,t)=>{let i=ege(r);if(!i.file)throw new TypeError("file is required");if(i.gzip)throw new TypeError("cannot append to compressed archives");if(!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");return e=Array.from(e),rge(i),tge(i,e,t)},rge=r=>{let e=r.filter;r.mtimeCache||(r.mtimeCache=new Map),r.filter=e?(t,i)=>e(t,i)&&!(r.mtimeCache.get(t)>i.mtime):(t,i)=>!(r.mtimeCache.get(t)>i.mtime)}});var _8=g((kOe,E8)=>{var{promisify:C8}=require("util"),ts=require("fs"),ige=r=>{if(!r)r={mode:511,fs:ts};else if(typeof r=="object")r={mode:511,fs:ts,...r};else if(typeof r=="number")r={mode:r,fs:ts};else if(typeof r=="string")r={mode:parseInt(r,8),fs:ts};else throw new TypeError("invalid options argument");return r.mkdir=r.mkdir||r.fs.mkdir||ts.mkdir,r.mkdirAsync=C8(r.mkdir),r.stat=r.stat||r.fs.stat||ts.stat,r.statAsync=C8(r.stat),r.statSync=r.statSync||r.fs.statSync||ts.statSync,r.mkdirSync=r.mkdirSync||r.fs.mkdirSync||ts.mkdirSync,r};E8.exports=ige});var T8=g((IOe,P8)=>{var nge=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,{resolve:oge,parse:sge}=require("path"),age=r=>{if(/\0/.test(r))throw Object.assign(new TypeError("path must be a string without null bytes"),{path:r,code:"ERR_INVALID_ARG_VALUE"});if(r=oge(r),nge==="win32"){let e=/[*|"<>?:]/,{root:t}=sge(r);if(e.test(r.substr(t.length)))throw Object.assign(new Error("Illegal characters in path."),{path:r,code:"EINVAL"})}return r};P8.exports=age});var A8=g((FOe,R8)=>{var{dirname:k8}=require("path"),I8=(r,e,t=void 0)=>t===e?Promise.resolve():r.statAsync(e).then(i=>i.isDirectory()?t:void 0,i=>i.code==="ENOENT"?I8(r,k8(e),e):void 0),F8=(r,e,t=void 0)=>{if(t!==e)try{return r.statSync(e).isDirectory()?t:void 0}catch(i){return i.code==="ENOENT"?F8(r,k8(e),e):void 0}};R8.exports={findMade:I8,findMadeSync:F8}});var NS=g((AOe,O8)=>{var{dirname:L8}=require("path"),LS=(r,e,t)=>{e.recursive=!1;let i=L8(r);return i===r?e.mkdirAsync(r,e).catch(n=>{if(n.code!=="EISDIR")throw n}):e.mkdirAsync(r,e).then(()=>t||r,n=>{if(n.code==="ENOENT")return LS(i,e).then(o=>LS(r,e,o));if(n.code!=="EEXIST"&&n.code!=="EROFS")throw n;return e.statAsync(r).then(o=>{if(o.isDirectory())return t;throw n},()=>{throw n})})},MS=(r,e,t)=>{let i=L8(r);if(e.recursive=!1,i===r)try{return e.mkdirSync(r,e)}catch(n){if(n.code!=="EISDIR")throw n;return}try{return e.mkdirSync(r,e),t||r}catch(n){if(n.code==="ENOENT")return MS(r,e,MS(i,e,t));if(n.code!=="EEXIST"&&n.code!=="EROFS")throw n;try{if(!e.statSync(r).isDirectory())throw n}catch(o){throw n}}};O8.exports={mkdirpManual:LS,mkdirpManualSync:MS}});var q8=g((OOe,M8)=>{var{dirname:N8}=require("path"),{findMade:lge,findMadeSync:uge}=A8(),{mkdirpManual:cge,mkdirpManualSync:fge}=NS(),pge=(r,e)=>(e.recursive=!0,N8(r)===r?e.mkdirAsync(r,e):lge(e,r).then(i=>e.mkdirAsync(r,e).then(()=>i).catch(n=>{if(n.code==="ENOENT")return cge(r,e);throw n}))),dge=(r,e)=>{if(e.recursive=!0,N8(r)===r)return e.mkdirSync(r,e);let i=uge(e,r);try{return e.mkdirSync(r,e),i}catch(n){if(n.code==="ENOENT")return fge(r,e);throw n}};M8.exports={mkdirpNative:pge,mkdirpNativeSync:dge}});var U8=g((LOe,$8)=>{var B8=require("fs"),hge=process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version,qS=hge.replace(/^v/,"").split("."),j8=+qS[0]>10||+qS[0]==10&&+qS[1]>=12,mge=j8?r=>r.mkdir===B8.mkdir:()=>!1,gge=j8?r=>r.mkdirSync===B8.mkdirSync:()=>!1;$8.exports={useNative:mge,useNativeSync:gge}});var K8=g((MOe,W8)=>{var vu=_8(),yu=T8(),{mkdirpNative:H8,mkdirpNativeSync:z8}=q8(),{mkdirpManual:G8,mkdirpManualSync:V8}=NS(),{useNative:vge,useNativeSync:yge}=U8(),bu=(r,e)=>(r=yu(r),e=vu(e),vge(e)?H8(r,e):G8(r,e)),bge=(r,e)=>(r=yu(r),e=vu(e),yge(e)?z8(r,e):V8(r,e));bu.sync=bge;bu.native=(r,e)=>H8(yu(r),vu(e));bu.manual=(r,e)=>G8(yu(r),vu(e));bu.nativeSync=(r,e)=>z8(yu(r),vu(e));bu.manualSync=(r,e)=>V8(yu(r),vu(e));W8.exports=bu});var tW=g((NOe,J8)=>{"use strict";var Fi=require("fs"),ga=require("path"),wge=Fi.lchown?"lchown":"chown",xge=Fi.lchownSync?"lchownSync":"chownSync",Y8=Fi.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),X8=(r,e,t)=>{try{return Fi[xge](r,e,t)}catch(i){if(i.code!=="ENOENT")throw i}},Dge=(r,e,t)=>{try{return Fi.chownSync(r,e,t)}catch(i){if(i.code!=="ENOENT")throw i}},Sge=Y8?(r,e,t,i)=>n=>{!n||n.code!=="EISDIR"?i(n):Fi.chown(r,e,t,i)}:(r,e,t,i)=>i,$S=Y8?(r,e,t)=>{try{return X8(r,e,t)}catch(i){if(i.code!=="EISDIR")throw i;Dge(r,e,t)}}:(r,e,t)=>X8(r,e,t),Ege=process.version,Z8=(r,e,t)=>Fi.readdir(r,e,t),Cge=(r,e)=>Fi.readdirSync(r,e);/^v4\./.test(Ege)&&(Z8=(r,e,t)=>Fi.readdir(r,t));var Zg=(r,e,t,i)=>{Fi[wge](r,e,t,Sge(r,e,t,n=>{i(n&&n.code!=="ENOENT"?n:null)}))},Q8=(r,e,t,i,n)=>{if(typeof e=="string")return Fi.lstat(ga.resolve(r,e),(o,s)=>{if(o)return n(o.code!=="ENOENT"?o:null);s.name=e,Q8(r,s,t,i,n)});if(e.isDirectory())BS(ga.resolve(r,e.name),t,i,o=>{if(o)return n(o);let s=ga.resolve(r,e.name);Zg(s,t,i,n)});else{let o=ga.resolve(r,e.name);Zg(o,t,i,n)}},BS=(r,e,t,i)=>{Z8(r,{withFileTypes:!0},(n,o)=>{if(n){if(n.code==="ENOENT")return i();if(n.code!=="ENOTDIR"&&n.code!=="ENOTSUP")return i(n)}if(n||!o.length)return Zg(r,e,t,i);let s=o.length,a=null,l=u=>{if(!a){if(u)return i(a=u);if(--s==0)return Zg(r,e,t,i)}};o.forEach(u=>Q8(r,u,e,t,l))})},_ge=(r,e,t,i)=>{if(typeof e=="string")try{let n=Fi.lstatSync(ga.resolve(r,e));n.name=e,e=n}catch(n){if(n.code==="ENOENT")return;throw n}e.isDirectory()&&eW(ga.resolve(r,e.name),t,i),$S(ga.resolve(r,e.name),t,i)},eW=(r,e,t)=>{let i;try{i=Cge(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR"||n.code==="ENOTSUP")return $S(r,e,t);throw n}return i&&i.length&&i.forEach(n=>_ge(r,n,e,t)),$S(r,e,t)};J8.exports=BS;BS.sync=eW});var oW=g((BOe,jS)=>{"use strict";var rW=K8(),Ai=require("fs"),Qg=require("path"),iW=tW(),US=class extends Error{constructor(e,t){super("Cannot extract through symbolic link");this.path=t,this.symlink=e}get name(){return"SylinkError"}},_p=class extends Error{constructor(e,t){super(t+": Cannot cd into '"+e+"'");this.path=e,this.code=t}get name(){return"CwdError"}},qOe=jS.exports=(r,e,t)=>{let i=e.umask,n=e.mode|448,o=(n&i)!=0,s=e.uid,a=e.gid,l=typeof s=="number"&&typeof a=="number"&&(s!==e.processUid||a!==e.processGid),u=e.preserve,c=e.unlink,f=e.cache,p=e.cwd,d=(y,v)=>{y?t(y):(f.set(r,!0),v&&l?iW(v,s,a,x=>d(x)):o?Ai.chmod(r,n,t):t())};if(f&&f.get(r)===!0)return d();if(r===p)return Ai.stat(r,(y,v)=>{(y||!v.isDirectory())&&(y=new _p(r,y&&y.code||"ENOTDIR")),d(y)});if(u)return rW(r,{mode:n}).then(y=>d(null,y),d);let m=Qg.relative(p,r).split(/\/|\\/);ev(p,m,n,f,c,p,null,d)},ev=(r,e,t,i,n,o,s,a)=>{if(!e.length)return a(null,s);let l=e.shift(),u=r+"/"+l;if(i.get(u))return ev(u,e,t,i,n,o,s,a);Ai.mkdir(u,t,nW(u,e,t,i,n,o,s,a))},nW=(r,e,t,i,n,o,s,a)=>l=>{if(l){if(l.path&&Qg.dirname(l.path)===o&&(l.code==="ENOTDIR"||l.code==="ENOENT"))return a(new _p(o,l.code));Ai.lstat(r,(u,c)=>{if(u)a(u);else if(c.isDirectory())ev(r,e,t,i,n,o,s,a);else if(n)Ai.unlink(r,f=>{if(f)return a(f);Ai.mkdir(r,t,nW(r,e,t,i,n,o,s,a))});else{if(c.isSymbolicLink())return a(new US(r,r+"/"+e.join("/")));a(l)}})}else s=s||r,ev(r,e,t,i,n,o,s,a)},$Oe=jS.exports.sync=(r,e)=>{let t=e.umask,i=e.mode|448,n=(i&t)!=0,o=e.uid,s=e.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==e.processUid||s!==e.processGid),l=e.preserve,u=e.unlink,c=e.cache,f=e.cwd,p=y=>{c.set(r,!0),y&&a&&iW.sync(y,o,s),n&&Ai.chmodSync(r,i)};if(c&&c.get(r)===!0)return p();if(r===f){let y=!1,v="ENOTDIR";try{y=Ai.statSync(r).isDirectory()}catch(x){v=x.code}finally{if(!y)throw new _p(r,v)}p();return}if(l)return p(rW.sync(r,i));let h=Qg.relative(f,r).split(/\/|\\/),m=null;for(let y=h.shift(),v=f;y&&(v+="/"+y);y=h.shift())if(!c.get(v))try{Ai.mkdirSync(v,i),m=m||v,c.set(v,!0)}catch(x){if(x.path&&Qg.dirname(x.path)===f&&(x.code==="ENOTDIR"||x.code==="ENOENT"))return new _p(f,x.code);let w=Ai.lstatSync(v);if(w.isDirectory()){c.set(v,!0);continue}else if(u){Ai.unlinkSync(v),Ai.mkdirSync(v,i),m=m||v,c.set(v,!0);continue}else if(w.isSymbolicLink())return new US(v,v+"/"+h.join("/"))}return p(m)}});var lW=g((jOe,sW)=>{var aW=require("assert");sW.exports=()=>{let r=new Map,e=new Map,{join:t}=require("path"),i=c=>t(c).split(/[\\\/]/).slice(0,-1).reduce((f,p)=>f.length?f.concat(t(f[f.length-1],p)):[p],[]),n=new Set,o=c=>{let f=e.get(c);if(!f)throw new Error("function does not have any path reservations");return{paths:f.paths.map(p=>r.get(p)),dirs:[...f.dirs].map(p=>r.get(p))}},s=c=>{let{paths:f,dirs:p}=o(c);return f.every(d=>d[0]===c)&&p.every(d=>d[0]instanceof Set&&d[0].has(c))},a=c=>n.has(c)||!s(c)?!1:(n.add(c),c(()=>l(c)),!0),l=c=>{if(!n.has(c))return!1;let{paths:f,dirs:p}=e.get(c),d=new Set;return f.forEach(h=>{let m=r.get(h);aW.equal(m[0],c),m.length===1?r.delete(h):(m.shift(),typeof m[0]=="function"?d.add(m[0]):m[0].forEach(y=>d.add(y)))}),p.forEach(h=>{let m=r.get(h);aW(m[0]instanceof Set),m[0].size===1&&m.length===1?r.delete(h):m[0].size===1?(m.shift(),d.add(m[0])):m[0].delete(c)}),n.delete(c),d.forEach(h=>a(h)),!0};return{check:s,reserve:(c,f)=>{let p=new Set(c.map(d=>i(d)).reduce((d,h)=>d.concat(h)));return e.set(f,{dirs:p,paths:c}),c.forEach(d=>{let h=r.get(d);h?h.push(f):r.set(d,[f])}),p.forEach(d=>{let h=r.get(d);h?h[h.length-1]instanceof Set?h[h.length-1].add(f):h.push(new Set([f])):r.set(d,[new Set([f])])}),a(f)}}}});var fW=g((UOe,uW)=>{var Pge=process.env.__FAKE_PLATFORM__||process.platform,Tge=Pge==="win32",Rge=global.__FAKE_TESTING_FS__||require("fs"),{O_CREAT:kge,O_TRUNC:Ige,O_WRONLY:Fge,UV_FS_O_FILEMAP:cW=0}=Rge.constants,Age=Tge&&!!cW,Oge=512*1024,Lge=cW|Ige|kge|Fge;uW.exports=Age?r=>r"w"});var XS=g((GOe,pW)=>{"use strict";var Mge=require("assert"),WOe=require("events").EventEmitter,Nge=Cp(),qe=require("fs"),qge=mu(),eo=require("path"),WS=oW(),HOe=WS.sync,dW=nS(),$ge=lW(),hW=Symbol("onEntry"),HS=Symbol("checkFs"),mW=Symbol("checkFs2"),zS=Symbol("isReusable"),to=Symbol("makeFs"),GS=Symbol("file"),VS=Symbol("directory"),tv=Symbol("link"),gW=Symbol("symlink"),vW=Symbol("hardlink"),yW=Symbol("unsupported"),zOe=Symbol("unknown"),bW=Symbol("checkPath"),wu=Symbol("mkdir"),xr=Symbol("onError"),rv=Symbol("pending"),wW=Symbol("pend"),xu=Symbol("unpend"),KS=Symbol("ended"),JS=Symbol("maybeClose"),YS=Symbol("skip"),Pp=Symbol("doChown"),Tp=Symbol("uid"),Rp=Symbol("gid"),xW=require("crypto"),DW=fW(),iv=()=>{throw new Error("sync function called cb somehow?!?")},Bge=(r,e)=>{if(process.platform!=="win32")return qe.unlink(r,e);let t=r+".DELETE."+xW.randomBytes(16).toString("hex");qe.rename(r,t,i=>{if(i)return e(i);qe.unlink(t,e)})},jge=r=>{if(process.platform!=="win32")return qe.unlinkSync(r);let e=r+".DELETE."+xW.randomBytes(16).toString("hex");qe.renameSync(r,e),qe.unlinkSync(e)},SW=(r,e,t)=>r===r>>>0?r:e===e>>>0?e:t,nv=class extends Nge{constructor(e){if(e||(e={}),e.ondone=t=>{this[KS]=!0,this[JS]()},super(e),this.reservations=$ge(),this.transform=typeof e.transform=="function"?e.transform:null,this.writable=!0,this.readable=!1,this[rv]=0,this[KS]=!1,this.dirCache=e.dirCache||new Map,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;e.preserveOwner===void 0&&typeof e.uid!="number"?this.preserveOwner=process.getuid&&process.getuid()===0:this.preserveOwner=!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||process.platform==="win32",this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=eo.resolve(e.cwd||process.cwd()),this.strip=+e.strip||0,this.processUmask=process.umask(),this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[hW](t))}warn(e,t,i={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(i.recoverable=!1),super.warn(e,t,i)}[JS](){this[KS]&&this[rv]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"),this.emit("close"))}[bW](e){if(this.strip){let t=e.path.split(/\/|\\/);if(t.length=this.strip&&(e.linkpath=i.slice(this.strip).join("/"))}}if(!this.preservePaths){let t=e.path;if(t.match(/(^|\/|\\)\.\.(\\|\/|$)/))return this.warn("TAR_ENTRY_ERROR","path contains '..'",{entry:e,path:t}),!1;if(eo.win32.isAbsolute(t)){let i=eo.win32.parse(t);e.path=t.substr(i.root.length);let n=i.root;this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:e,path:t})}}if(this.win32){let t=eo.win32.parse(e.path);e.path=t.root===""?dW.encode(e.path):t.root+dW.encode(e.path.substr(t.root.length))}return eo.isAbsolute(e.path)?e.absolute=e.path:e.absolute=eo.resolve(this.cwd,e.path),!0}[hW](e){if(!this[bW](e))return e.resume();switch(Mge.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[HS](e);case"CharacterDevice":case"BlockDevice":case"FIFO":return this[yW](e)}}[xr](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[xu](),t.resume())}[wu](e,t,i){WS(e,{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t},i)}[Pp](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Tp](e){return SW(this.uid,e.uid,this.processUid)}[Rp](e){return SW(this.gid,e.gid,this.processGid)}[GS](e,t){let i=e.mode&4095||this.fmode,n=new qge.WriteStream(e.absolute,{flags:DW(e.size),mode:i,autoClose:!1});n.on("error",l=>this[xr](l,e));let o=1,s=l=>{if(l)return this[xr](l,e);--o==0&&qe.close(n.fd,u=>{t(),u?this[xr](u,e):this[xu]()})};n.on("finish",l=>{let u=e.absolute,c=n.fd;if(e.mtime&&!this.noMtime){o++;let f=e.atime||new Date,p=e.mtime;qe.futimes(c,f,p,d=>d?qe.utimes(u,f,p,h=>s(h&&d)):s())}if(this[Pp](e)){o++;let f=this[Tp](e),p=this[Rp](e);qe.fchown(c,f,p,d=>d?qe.chown(u,f,p,h=>s(h&&d)):s())}s()});let a=this.transform&&this.transform(e)||e;a!==e&&(a.on("error",l=>this[xr](l,e)),e.pipe(a)),a.pipe(n)}[VS](e,t){let i=e.mode&4095||this.dmode;this[wu](e.absolute,i,n=>{if(n)return t(),this[xr](n,e);let o=1,s=a=>{--o==0&&(t(),this[xu](),e.resume())};e.mtime&&!this.noMtime&&(o++,qe.utimes(e.absolute,e.atime||new Date,e.mtime,s)),this[Pp](e)&&(o++,qe.chown(e.absolute,this[Tp](e),this[Rp](e),s)),s()})}[yW](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[gW](e,t){this[tv](e,e.linkpath,"symlink",t)}[vW](e,t){this[tv](e,eo.resolve(this.cwd,e.linkpath),"link",t)}[wW](){this[rv]++}[xu](){this[rv]--,this[JS]()}[YS](e){this[xu](),e.resume()}[zS](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&process.platform!=="win32"}[HS](e){this[wW]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,i=>this[mW](e,i))}[mW](e,t){this[wu](eo.dirname(e.absolute),this.dmode,i=>{if(i)return t(),this[xr](i,e);qe.lstat(e.absolute,(n,o)=>{o&&(this.keep||this.newer&&o.mtime>e.mtime)?(this[YS](e),t()):n||this[zS](e,o)?this[to](null,e,t):o.isDirectory()?e.type==="Directory"?!e.mode||(o.mode&4095)===e.mode?this[to](null,e,t):qe.chmod(e.absolute,e.mode,s=>this[to](s,e,t)):qe.rmdir(e.absolute,s=>this[to](s,e,t)):Bge(e.absolute,s=>this[to](s,e,t))})})}[to](e,t,i){if(e)return this[xr](e,t);switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[GS](t,i);case"Link":return this[vW](t,i);case"SymbolicLink":return this[gW](t,i);case"Directory":case"GNUDumpDir":return this[VS](t,i)}}[tv](e,t,i,n){qe[i](t,e.absolute,o=>{if(o)return this[xr](o,e);n(),this[xu](),e.resume()})}},EW=class extends nv{constructor(e){super(e)}[HS](e){let t=this[wu](eo.dirname(e.absolute),this.dmode,iv);if(t)return this[xr](t,e);try{let i=qe.lstatSync(e.absolute);if(this.keep||this.newer&&i.mtime>e.mtime)return this[YS](e);if(this[zS](e,i))return this[to](null,e,iv);try{return i.isDirectory()?e.type==="Directory"?e.mode&&(i.mode&4095)!==e.mode&&qe.chmodSync(e.absolute,e.mode):qe.rmdirSync(e.absolute):jge(e.absolute),this[to](null,e,iv)}catch(n){return this[xr](n,e)}}catch(i){return this[to](null,e,iv)}}[GS](e,t){let i=e.mode&4095||this.fmode,n=l=>{let u;try{qe.closeSync(s)}catch(c){u=c}(l||u)&&this[xr](l||u,e)},o,s;try{s=qe.openSync(e.absolute,DW(e.size),i)}catch(l){return n(l)}let a=this.transform&&this.transform(e)||e;a!==e&&(a.on("error",l=>this[xr](l,e)),e.pipe(a)),a.on("data",l=>{try{qe.writeSync(s,l,0,l.length)}catch(u){n(u)}}),a.on("end",l=>{let u=null;if(e.mtime&&!this.noMtime){let c=e.atime||new Date,f=e.mtime;try{qe.futimesSync(s,c,f)}catch(p){try{qe.utimesSync(e.absolute,c,f)}catch(d){u=p}}}if(this[Pp](e)){let c=this[Tp](e),f=this[Rp](e);try{qe.fchownSync(s,c,f)}catch(p){try{qe.chownSync(e.absolute,c,f)}catch(d){u=u||p}}}n(u)})}[VS](e,t){let i=e.mode&4095||this.dmode,n=this[wu](e.absolute,i);if(n)return this[xr](n,e);if(e.mtime&&!this.noMtime)try{qe.utimesSync(e.absolute,e.atime||new Date,e.mtime)}catch(o){}if(this[Pp](e))try{qe.chownSync(e.absolute,this[Tp](e),this[Rp](e))}catch(o){}e.resume()}[wu](e,t){try{return WS.sync(e,{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t})}catch(i){return i}}[tv](e,t,i,n){try{qe[i+"Sync"](t,e.absolute),e.resume()}catch(o){return this[xr](o,e)}}};nv.Sync=EW;pW.exports=nv});var RW=g((KOe,CW)=>{"use strict";var Uge=tu(),ov=XS(),_W=require("fs"),PW=mu(),TW=require("path"),VOe=CW.exports=(r,e,t)=>{typeof r=="function"?(t=r,e=null,r={}):Array.isArray(r)&&(e=r,r={}),typeof e=="function"&&(t=e,e=null),e?e=Array.from(e):e=[];let i=Uge(r);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return e.length&&Wge(i,e),i.file&&i.sync?Hge(i):i.file?zge(i,t):i.sync?Gge(i):Vge(i)},Wge=(r,e)=>{let t=new Map(e.map(o=>[o.replace(/\/+$/,""),!0])),i=r.filter,n=(o,s)=>{let a=s||TW.parse(o).root||".",l=o===a?!1:t.has(o)?t.get(o):n(TW.dirname(o),a);return t.set(o,l),l};r.filter=i?(o,s)=>i(o,s)&&n(o.replace(/\/+$/,"")):o=>n(o.replace(/\/+$/,""))},Hge=r=>{let e=new ov.Sync(r),t=r.file,i=!0,n,o=_W.statSync(t),s=r.maxReadSize||16*1024*1024;new PW.ReadStreamSync(t,{readSize:s,size:o.size}).pipe(e)},zge=(r,e)=>{let t=new ov(r),i=r.maxReadSize||16*1024*1024,n=r.file,o=new Promise((s,a)=>{t.on("error",a),t.on("close",s),_W.stat(n,(l,u)=>{if(l)a(l);else{let c=new PW.ReadStream(n,{readSize:i,size:u.size});c.on("error",a),c.pipe(t)}})});return e?o.then(e,e):o},Gge=r=>new ov.Sync(r),Vge=r=>new ov(r)});var kW=g(It=>{"use strict";It.c=It.create=h8();It.r=It.replace=OS();It.t=It.list=Yg();It.u=It.update=S8();It.x=It.extract=RW();It.Pack=qg();It.Unpack=XS();It.Parse=Cp();It.ReadEntry=bp();It.WriteEntry=fS();It.Header=ou();It.Pax=Eg();It.types=yp()});var OW=g((YOe,IW)=>{IW.exports=cr;function cr(r){if(!(this instanceof cr))return new cr(r);this.value=r}cr.prototype.get=function(r){for(var e=this.value,t=0;t{var Kge=OW(),Jge=require("events").EventEmitter;LW.exports=Du;function Du(r){var e=Du.saw(r,{}),t=r.call(e.handlers,e);return t!==void 0&&(e.handlers=t),e.record(),e.chain()}Du.light=function(e){var t=Du.saw(e,{}),i=e.call(t.handlers,t);return i!==void 0&&(t.handlers=i),t.chain()};Du.saw=function(r,e){var t=new Jge;return t.handlers=e,t.actions=[],t.chain=function(){var i=Kge(t.handlers).map(function(n){if(this.isRoot)return n;var o=this.path;typeof n=="function"&&this.update(function(){return t.actions.push({path:o,args:[].slice.call(arguments)}),i})});return process.nextTick(function(){t.emit("begin"),t.next()}),i},t.pop=function(){return t.actions.shift()},t.next=function(){var i=t.pop();if(!i)t.emit("end");else if(!i.trap){var n=t.handlers;i.path.forEach(function(o){n=n[o]}),n.apply(t.handlers,i.args)}},t.nest=function(i){var n=[].slice.call(arguments,1),o=!0;if(typeof i=="boolean"){var o=i;i=n.shift()}var s=Du.saw(r,{}),a=r.call(s.handlers,s);a!==void 0&&(s.handlers=a),typeof t.step!="undefined"&&s.record(),i.apply(s.chain(),n),o!==!1&&s.on("end",t.next)},t.record=function(){Yge(t)},["trap","down","jump"].forEach(function(i){t[i]=function(){throw new Error("To use the trap, down and jump features, please call record() first to start recording actions.")}}),t};function Yge(r){r.step=0,r.pop=function(){return r.actions[r.step++]},r.trap=function(e,t){var i=Array.isArray(e)?e:[e];r.actions.push({path:i,step:r.step,cb:t,trap:!0})},r.down=function(e){var t=(Array.isArray(e)?e:[e]).join("/"),i=r.actions.slice(r.step).map(function(o){return o.trap&&o.step<=r.step?!1:o.path.join("/")==t}).indexOf(!0);i>=0?r.step+=i:r.step=r.actions.length;var n=r.actions[r.step-1];n&&n.trap?(r.step=n.step,n.cb()):r.next()},r.jump=function(e){r.step=e,r.next()}}});var qW=g((ZOe,NW)=>{NW.exports=Dr;function Dr(r){if(!(this instanceof Dr))return new Dr(r);this.buffers=r||[],this.length=this.buffers.reduce(function(e,t){return e+t.length},0)}Dr.prototype.push=function(){for(var r=0;r=0?r:this.length-r,n=[].slice.call(arguments,2);e===void 0?e=this.length-i:e>this.length-i&&(e=this.length-i);for(var r=0;r0){var u=i-a;if(u+e0){var d=n.slice();d.unshift(f),d.push(p),t.splice.apply(t,[l,1].concat(d)),l+=d.length,n=[]}else t.splice(l,1,f,p),l+=2}else o.push(t[l].slice(u)),t[l]=t[l].slice(0,u),l++}for(n.length>0&&(t.splice.apply(t,[l,0].concat(n)),l+=n.length);o.lengththis.length&&(e=this.length);for(var i=0,n=0;n=e-r?Math.min(u+(e-r)-s,l):l;t[a].copy(o,s,u,c),s+=c-u}return o};Dr.prototype.pos=function(r){if(r<0||r>=this.length)throw new Error("oob");for(var e=r,t=0,i=null;;){if(i=this.buffers[t],e=this.buffers[t].length;)if(i=0,t++,t>=this.buffers.length)return-1;var l=this.buffers[t][i];if(l==r[n]){if(n==0&&(o={i:t,j:i,pos:s}),n++,n==r.length)return o.pos}else n!=0&&(t=o.i,i=o.j,s=o.pos,n=0);i++,s++}};Dr.prototype.toBuffer=function(){return this.slice()};Dr.prototype.toString=function(r,e,t){return this.slice(e,t).toString(r)}});var BW=g((QOe,$W)=>{$W.exports=function(r){function e(i,n){var o=t.store,s=i.split(".");s.slice(0,-1).forEach(function(l){o[l]===void 0&&(o[l]={}),o=o[l]});var a=s[s.length-1];return arguments.length==1?o[a]:o[a]=n}var t={get:function(i){return e(i)},set:function(i,n){return e(i,n)},store:r||{}};return t}});var GW=g((va,jW)=>{var Xge=MW(),UW=require("events").EventEmitter,Zge=qW(),sv=BW(),Qge=require("stream").Stream;va=jW.exports=function(r,e){if(Buffer.isBuffer(r))return va.parse(r);var t=va.stream();return r&&r.pipe?r.pipe(t):r&&(r.on(e||"data",function(i){t.write(i)}),r.on("end",function(){t.end()})),t};va.stream=function(r){if(r)return va.apply(null,arguments);var e=null;function t(f,p,d){e={bytes:f,skip:d,cb:function(h){e=null,p(h)}},n()}var i=null;function n(){if(!e){c&&(u=!0);return}if(typeof e=="function")e();else{var f=i+e.bytes;if(a.length>=f){var p;i==null?(p=a.splice(0,f),e.skip||(p=p.slice())):(e.skip||(p=a.slice(i,f)),i=f),e.skip?e.cb():e.cb(p)}}}function o(f){function p(){u||f.next()}var d=WW(function(h,m){return function(y){t(h,function(v){l.set(y,m(v)),p()})}});return d.tap=function(h){f.nest(h,l.store)},d.into=function(h,m){l.get(h)||l.set(h,{});var y=l;l=sv(y.get(h)),f.nest(function(){m.apply(this,arguments),this.tap(function(){l=y})},l.store)},d.flush=function(){l.store={},p()},d.loop=function(h){var m=!1;f.nest(!1,function y(){this.vars=l.store,h.call(this,function(){m=!0,p()},l.store),this.tap(function(){m?f.next():y.call(this)}.bind(this))},l.store)},d.buffer=function(h,m){typeof m=="string"&&(m=l.get(m)),t(m,function(y){l.set(h,y),p()})},d.skip=function(h){typeof h=="string"&&(h=l.get(h)),t(h,function(){p()})},d.scan=function(m,y){if(typeof y=="string")y=new Buffer(y);else if(!Buffer.isBuffer(y))throw new Error("search must be a Buffer or a string");var v=0;e=function(){var x=a.indexOf(y,i+v),w=x-i-v;x!==-1?(e=null,i!=null?(l.set(m,a.slice(i,i+v+w)),i+=v+w+y.length):(l.set(m,a.slice(0,v+w)),a.splice(0,v+w+y.length)),p(),n()):w=Math.max(a.length-y.length-i-v,0),v+=w},n()},d.peek=function(h){i=0,f.nest(function(){h.call(this,l.store),this.tap(function(){i=null})})},d}var s=Xge.light(o);s.writable=!0;var a=Zge();s.write=function(f){a.push(f),n()};var l=sv(),u=!1,c=!1;return s.end=function(){c=!0},s.pipe=Qge.prototype.pipe,Object.getOwnPropertyNames(UW.prototype).forEach(function(f){s[f]=UW.prototype[f]}),s};va.parse=function(e){var t=WW(function(o,s){return function(a){if(i+o<=e.length){var l=e.slice(i,i+o);i+=o,n.set(a,s(l))}else n.set(a,null);return t}}),i=0,n=sv();return t.vars=n.store,t.tap=function(o){return o.call(t,n.store),t},t.into=function(o,s){n.get(o)||n.set(o,{});var a=n;return n=sv(a.get(o)),s.call(t,n.store),n=a,t},t.loop=function(o){for(var s=!1,a=function(){s=!0};s===!1;)o.call(t,a,n.store);return t},t.buffer=function(o,s){typeof s=="string"&&(s=n.get(s));var a=e.slice(i,Math.min(e.length,i+s));return i+=s,n.set(o,a),t},t.skip=function(o){return typeof o=="string"&&(o=n.get(o)),i+=o,t},t.scan=function(o,s){if(typeof s=="string")s=new Buffer(s);else if(!Buffer.isBuffer(s))throw new Error("search must be a Buffer or a string");n.set(o,null);for(var a=0;a+i<=e.length-s.length+1;a++){for(var l=0;l=e.length},t};function HW(r){for(var e=0,t=0;t{var KW=require("stream").Transform,rve=require("util");function ya(r,e){if(!(this instanceof ya))return new ya;KW.call(this);var t=typeof r=="object"?r.pattern:r;this.pattern=Buffer.isBuffer(t)?t:Buffer.from(t),this.requiredLength=this.pattern.length,r.requiredExtraSize&&(this.requiredLength+=r.requiredExtraSize),this.data=new Buffer(""),this.bytesSoFar=0,this.matchFn=e}rve.inherits(ya,KW);ya.prototype.checkDataChunk=function(r){var e=this.data.length>=this.requiredLength;if(!!e){var t=this.data.indexOf(this.pattern,r?1:0);if(t>=0&&t+this.requiredLength>this.data.length){if(t>0){var i=this.data.slice(0,t);this.push(i),this.bytesSoFar+=t,this.data=this.data.slice(t)}return}if(t===-1){var n=this.data.length-this.requiredLength+1,i=this.data.slice(0,n);this.push(i),this.bytesSoFar+=n,this.data=this.data.slice(n);return}if(t>0){var i=this.data.slice(0,t);this.data=this.data.slice(t),this.push(i),this.bytesSoFar+=t}var o=this.matchFn?this.matchFn(this.data,this.bytesSoFar):!0;if(o){this.data=new Buffer("");return}return!0}};ya.prototype._transform=function(r,e,t){this.data=Buffer.concat([this.data,r]);for(var i=!0;this.checkDataChunk(!i);)i=!1;t()};ya.prototype._flush=function(r){if(this.data.length>0)for(var e=!0;this.checkDataChunk(!e);)e=!1;this.data.length>0&&(this.push(this.data),this.data=null),r()};VW.exports=ya});var XW=g((tLe,YW)=>{"use strict";var ZS=require("stream"),ive=require("util").inherits;function kp(){if(!(this instanceof kp))return new kp;ZS.PassThrough.call(this),this.path=null,this.type=null,this.isDirectory=!1}ive(kp,ZS.PassThrough);kp.prototype.autodrain=function(){return this.pipe(new ZS.Transform({transform:function(r,e,t){t()}}))};YW.exports=kp});var eE=g((rLe,ZW)=>{"use strict";var rs=GW(),QS=require("stream"),nve=require("util"),ove=require("zlib"),sve=JW(),QW=XW(),oe={STREAM_START:0,START:1,LOCAL_FILE_HEADER:2,LOCAL_FILE_HEADER_SUFFIX:3,FILE_DATA:4,FILE_DATA_END:5,DATA_DESCRIPTOR:6,CENTRAL_DIRECTORY_FILE_HEADER:7,CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:8,CDIR64_END:9,CDIR64_END_DATA_SECTOR:10,CDIR64_LOCATOR:11,CENTRAL_DIRECTORY_END:12,CENTRAL_DIRECTORY_END_COMMENT:13,TRAILING_JUNK:14,ERROR:99},Ip=4294967296,ave=67324752,lve=134695760,uve=33639248,cve=101075792,fve=117853008,pve=101010256;function zt(r){if(!(this instanceof zt))return new zt(r);QS.Transform.call(this),this.options=r||{},this.data=new Buffer(""),this.state=oe.STREAM_START,this.skippedBytes=0,this.parsedEntity=null,this.outStreamInfo={}}nve.inherits(zt,QS.Transform);zt.prototype.processDataChunk=function(r){var e;switch(this.state){case oe.STREAM_START:case oe.START:e=4;break;case oe.LOCAL_FILE_HEADER:e=26;break;case oe.LOCAL_FILE_HEADER_SUFFIX:e=this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength;break;case oe.DATA_DESCRIPTOR:e=12;break;case oe.CENTRAL_DIRECTORY_FILE_HEADER:e=42;break;case oe.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:e=this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength+this.parsedEntity.fileCommentLength;break;case oe.CDIR64_END:e=52;break;case oe.CDIR64_END_DATA_SECTOR:e=this.parsedEntity.centralDirectoryRecordSize-44;break;case oe.CDIR64_LOCATOR:e=16;break;case oe.CENTRAL_DIRECTORY_END:e=18;break;case oe.CENTRAL_DIRECTORY_END_COMMENT:e=this.parsedEntity.commentLength;break;case oe.FILE_DATA:return 0;case oe.FILE_DATA_END:return 0;case oe.TRAILING_JUNK:return this.options.debug&&console.log("found",r.length,"bytes of TRAILING_JUNK"),r.length;default:return r.length}var t=r.length;if(t>>8,(o&255)==80){s=a;break}return this.skippedBytes+=s,this.options.debug&&console.log("Skipped",this.skippedBytes,"bytes"),s}this.state=oe.ERROR;var l=n?"Not a valid zip file":"Invalid signature in zip file";if(this.options.debug){var u=r.readUInt32LE(0),c;try{c=r.slice(0,4).toString()}catch(E){}console.log("Unexpected signature in zip file: 0x"+u.toString(16),'"'+c+'", skipped',this.skippedBytes,"bytes")}return this.emit("error",new Error(l)),r.length}return this.skippedBytes=0,e;case oe.LOCAL_FILE_HEADER:return this.parsedEntity=this._readFile(r),this.state=oe.LOCAL_FILE_HEADER_SUFFIX,e;case oe.LOCAL_FILE_HEADER_SUFFIX:var f=new QW,p=(this.parsedEntity.flags&2048)!=0;f.path=this._decodeString(r.slice(0,this.parsedEntity.fileNameLength),p);var d=r.slice(this.parsedEntity.fileNameLength,this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength),h=this._readExtraFields(d);if(h&&h.parsed&&(h.parsed.path&&!p&&(f.path=h.parsed.path),Number.isFinite(h.parsed.uncompressedSize)&&this.parsedEntity.uncompressedSize===Ip-1&&(this.parsedEntity.uncompressedSize=h.parsed.uncompressedSize),Number.isFinite(h.parsed.compressedSize)&&this.parsedEntity.compressedSize===Ip-1&&(this.parsedEntity.compressedSize=h.parsed.compressedSize)),this.parsedEntity.extra=h.parsed||{},this.options.debug){let E=Object.assign({},this.parsedEntity,{path:f.path,flags:"0x"+this.parsedEntity.flags.toString(16),extraFields:h&&h.debug});console.log("decoded LOCAL_FILE_HEADER:",JSON.stringify(E,null,2))}return this._prepareOutStream(this.parsedEntity,f),this.emit("entry",f),this.state=oe.FILE_DATA,e;case oe.CENTRAL_DIRECTORY_FILE_HEADER:return this.parsedEntity=this._readCentralDirectoryEntry(r),this.state=oe.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX,e;case oe.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:var p=(this.parsedEntity.flags&2048)!=0,m=this._decodeString(r.slice(0,this.parsedEntity.fileNameLength),p),d=r.slice(this.parsedEntity.fileNameLength,this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength),h=this._readExtraFields(d);h&&h.parsed&&h.parsed.path&&!p&&(m=h.parsed.path),this.parsedEntity.extra=h.parsed;var y=(this.parsedEntity.versionMadeBy&65280)>>8==3,v,x;if(y){v=this.parsedEntity.externalFileAttributes>>>16;var w=v>>>12;x=(w&10)==10}if(this.options.debug){let E=Object.assign({},this.parsedEntity,{path:m,flags:"0x"+this.parsedEntity.flags.toString(16),unixAttrs:v&&"0"+v.toString(8),isSymlink:x,extraFields:h.debug});console.log("decoded CENTRAL_DIRECTORY_FILE_HEADER:",JSON.stringify(E,null,2))}return this.state=oe.START,e;case oe.CDIR64_END:return this.parsedEntity=this._readEndOfCentralDirectory64(r),this.options.debug&&console.log("decoded CDIR64_END_RECORD:",this.parsedEntity),this.state=oe.CDIR64_END_DATA_SECTOR,e;case oe.CDIR64_END_DATA_SECTOR:return this.state=oe.START,e;case oe.CDIR64_LOCATOR:return this.state=oe.START,e;case oe.CENTRAL_DIRECTORY_END:return this.parsedEntity=this._readEndOfCentralDirectory(r),this.options.debug&&console.log("decoded CENTRAL_DIRECTORY_END:",this.parsedEntity),this.state=oe.CENTRAL_DIRECTORY_END_COMMENT,e;case oe.CENTRAL_DIRECTORY_END_COMMENT:return this.options.debug&&console.log("decoded CENTRAL_DIRECTORY_END_COMMENT:",r.slice(0,e).toString()),this.state=oe.TRAILING_JUNK,e;case oe.ERROR:return r.length;default:return console.log("didn't handle state #",this.state,"discarding"),r.length}};zt.prototype._prepareOutStream=function(r,e){var t=this,i=r.uncompressedSize===0&&/[\/\\]$/.test(e.path);e.path=e.path.replace(/^([/\\]*[.]+[/\\]+)*[/\\]*/,""),e.type=i?"Directory":"File",e.isDirectory=i;var n=!(r.flags&8);n&&(e.size=r.uncompressedSize);var o=r.versionsNeededToExtract<=45;if(this.outStreamInfo={stream:null,limit:n?r.compressedSize:-1,written:0},n)this.outStreamInfo.stream=new QS.PassThrough;else{var s=new Buffer(4);s.writeUInt32LE(lve,0);var a=r.extra.zip64Mode,l=a?20:12,u={pattern:s,requiredExtraSize:l},c=new sve(u,function(m,y){var v=t._readDataDescriptor(m,a),x=v.compressedSize===y;if(!a&&!x&&y>=Ip)for(var w=y-Ip;w>=0&&(x=v.compressedSize===w,!x);)w-=Ip;if(!!x){t.state=oe.FILE_DATA_END;var E=a?24:16;return t.data.length>0?t.data=Buffer.concat([m.slice(E),t.data]):t.data=m.slice(E),!0}});this.outStreamInfo.stream=c}var f=r.flags&1||r.flags&64;if(f||!o){var p=f?"Encrypted files are not supported!":"Zip version "+Math.floor(r.versionsNeededToExtract/10)+"."+r.versionsNeededToExtract%10+" is not supported";e.skip=!0,setImmediate(()=>{e.emit("error",new Error(p))}),this.outStreamInfo.stream.pipe(new QW().autodrain());return}var d=r.compressionMethod>0;if(d){var h=ove.createInflateRaw();h.on("error",function(m){t.state=oe.ERROR,t.emit("error",m)}),this.outStreamInfo.stream.pipe(h).pipe(e)}else this.outStreamInfo.stream.pipe(e);this._drainAllEntries&&e.autodrain()};zt.prototype._readFile=function(r){var e=rs.parse(r).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return e};zt.prototype._readExtraFields=function(r){var e={},t={parsed:e};this.options.debug&&(t.debug=[]);for(var i=0;i=l+4&&a&1&&(e.mtime=new Date(r.readUInt32LE(i+l)*1e3),l+=4),n.extraSize>=l+4&&a&2&&(e.atime=new Date(r.readUInt32LE(i+l)*1e3),l+=4),n.extraSize>=l+4&&a&4&&(e.ctime=new Date(r.readUInt32LE(i+l)*1e3));break;case 28789:o="Info-ZIP Unicode Path Extra Field";var u=r.readUInt8(i);if(u===1){var l=1,c=r.readUInt32LE(i+l);l+=4;var f=r.slice(i+l);e.path=f.toString()}break;case 13:case 22613:o=n.extraId===13?"PKWARE Unix":"Info-ZIP UNIX (type 1)";var l=0;if(n.extraSize>=8){var p=new Date(r.readUInt32LE(i+l)*1e3);l+=4;var d=new Date(r.readUInt32LE(i+l)*1e3);if(l+=4,e.atime=p,e.mtime=d,n.extraSize>=12){var h=r.readUInt16LE(i+l);l+=2;var m=r.readUInt16LE(i+l);l+=2,e.uid=h,e.gid=m}}break;case 30805:o="Info-ZIP UNIX (type 2)";var l=0;if(n.extraSize>=4){var h=r.readUInt16LE(i+l);l+=2;var m=r.readUInt16LE(i+l);l+=2,e.uid=h,e.gid=m}break;case 30837:o="Info-ZIP New Unix";var l=0,y=r.readUInt8(i);if(l+=1,y===1){var v=r.readUInt8(i+l);l+=1,v<=6&&(e.uid=r.readUIntLE(i+l,v)),l+=v;var x=r.readUInt8(i+l);l+=1,x<=6&&(e.gid=r.readUIntLE(i+l,x))}break;case 30062:o="ASi Unix";var l=0;if(n.extraSize>=14){var w=r.readUInt32LE(i+l);l+=4;var E=r.readUInt16LE(i+l);l+=2;var P=r.readUInt32LE(i+l);l+=4;var h=r.readUInt16LE(i+l);l+=2;var m=r.readUInt16LE(i+l);if(l+=2,e.mode=E,e.uid=h,e.gid=m,n.extraSize>14){var k=i+l,_=i+n.extraSize-14,O=this._decodeString(r.slice(k,_));e.symlink=O}}break}this.options.debug&&t.debug.push({extraId:"0x"+n.extraId.toString(16),description:o,data:r.slice(i,i+n.extraSize).inspect()}),i+=n.extraSize}return t};zt.prototype._readDataDescriptor=function(r,e){if(e){var t=rs.parse(r).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars;return t}var t=rs.parse(r).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars;return t};zt.prototype._readCentralDirectoryEntry=function(r){var e=rs.parse(r).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return e};zt.prototype._readEndOfCentralDirectory64=function(r){var e=rs.parse(r).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;return e};zt.prototype._readEndOfCentralDirectory=function(r){var e=rs.parse(r).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars;return e};var dve="\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 ";zt.prototype._decodeString=function(r,e){if(e)return r.toString("utf8");if(this.options.decodeString)return this.options.decodeString(r);let t="";for(var i=0;i0&&(this.data=this.data.slice(t),this.data.length!==0););if(this.state===oe.FILE_DATA){if(this.outStreamInfo.limit>=0){var i=this.outStreamInfo.limit-this.outStreamInfo.written,n;i{if(this.state===oe.FILE_DATA_END)return this.state=oe.START,o.end(e);e()})}return}e()};zt.prototype.drainAll=function(){this._drainAllEntries=!0};zt.prototype._transform=function(r,e,t){var i=this;i.data.length>0?i.data=Buffer.concat([i.data,r]):i.data=r;var n=i.data.length,o=function(){if(i.data.length>0&&i.data.length0){e._parseOrOutput("buffer",function(){if(e.data.length>0)return setImmediate(function(){e._flush(r)});r()});return}if(e.state===oe.FILE_DATA)return r(new Error("Stream finished in an invalid state, uncompression failed"));setImmediate(r)};ZW.exports=zt});var t5=g((iLe,e5)=>{var Fp=require("stream").Transform,hve=require("util"),mve=eE();function is(r){if(!(this instanceof is))return new is(r);var e=r||{};Fp.call(this,{readableObjectMode:!0}),this.opts=r||{},this.unzipStream=new mve(this.opts);var t=this;this.unzipStream.on("entry",function(i){t.push(i)}),this.unzipStream.on("error",function(i){t.emit("error",i)})}hve.inherits(is,Fp);is.prototype._transform=function(r,e,t){this.unzipStream.write(r,e,t)};is.prototype._flush=function(r){var e=this;this.unzipStream.end(function(){process.nextTick(function(){e.emit("close")}),r()})};is.prototype.on=function(r,e){return r==="entry"?Fp.prototype.on.call(this,"data",e):Fp.prototype.on.call(this,r,e)};is.prototype.drainAll=function(){return this.unzipStream.drainAll(),this.pipe(new Fp({objectMode:!0,transform:function(r,e,t){t()}}))};e5.exports=is});var o5=g((nLe,r5)=>{var Ap=require("path"),i5=require("fs"),n5=parseInt("0777",8);r5.exports=Su.mkdirp=Su.mkdirP=Su;function Su(r,e,t,i){typeof e=="function"?(t=e,e={}):(!e||typeof e!="object")&&(e={mode:e});var n=e.mode,o=e.fs||i5;n===void 0&&(n=n5),i||(i=null);var s=t||function(){};r=Ap.resolve(r),o.mkdir(r,n,function(a){if(!a)return i=i||r,s(null,i);switch(a.code){case"ENOENT":if(Ap.dirname(r)===r)return s(a);Su(Ap.dirname(r),e,function(l,u){l?s(l,u):Su(r,e,s,u)});break;default:o.stat(r,function(l,u){l||!u.isDirectory()?s(a,i):s(null,i)});break}})}Su.sync=function r(e,t,i){(!t||typeof t!="object")&&(t={mode:t});var n=t.mode,o=t.fs||i5;n===void 0&&(n=n5),i||(i=null),e=Ap.resolve(e);try{o.mkdirSync(e,n),i=i||e}catch(a){switch(a.code){case"ENOENT":i=r(Ap.dirname(e),t,i),r(e,t,i);break;default:var s;try{s=o.statSync(e)}catch(l){throw a}if(!s.isDirectory())throw a;break}}return i}});var u5=g((oLe,s5)=>{var gve=require("fs"),a5=require("path"),vve=require("util"),yve=o5(),l5=require("stream").Transform,bve=eE();function ns(r){if(!(this instanceof ns))return new ns(r);l5.call(this),this.opts=r||{},this.unzipStream=new bve(this.opts),this.unfinishedEntries=0,this.afterFlushWait=!1,this.createdDirectories={};var e=this;this.unzipStream.on("entry",this._processEntry.bind(this)),this.unzipStream.on("error",function(t){e.emit("error",t)})}vve.inherits(ns,l5);ns.prototype._transform=function(r,e,t){this.unzipStream.write(r,e,t)};ns.prototype._flush=function(r){var e=this,t=function(){process.nextTick(function(){e.emit("close")}),r()};this.unzipStream.end(function(){if(e.unfinishedEntries>0)return e.afterFlushWait=!0,e.on("await-finished",t);t()})};ns.prototype._processEntry=function(r){var e=this,t=a5.join(this.opts.path,r.path),i=r.isDirectory?t:a5.dirname(t);this.unfinishedEntries++;var n=function(){var o=gve.createWriteStream(t);o.on("close",function(){e.unfinishedEntries--,e._notifyAwaiter()}),o.on("error",function(s){e.emit("error",s)}),r.pipe(o)};if(this.createdDirectories[i]||i===".")return n();yve(i,function(o){if(o)return e.emit("error",o);if(e.createdDirectories[i]=!0,r.isDirectory){e.unfinishedEntries--,e._notifyAwaiter();return}n()})};ns.prototype._notifyAwaiter=function(){this.afterFlushWait&&this.unfinishedEntries===0&&(this.emit("await-finished"),this.afterFlushWait=!1)};s5.exports=ns});var c5=g(tE=>{"use strict";tE.Parse=t5();tE.Extract=u5()});var p5=g((aLe,f5)=>{"use strict";function wve(){}function av(r,e){let t=av.spread(r,e),i=t.then(n=>n[0]);return i.cancel=t.cancel,i}(function(r){function e(t,i){let n=null,o=new Promise((s,a)=>{function l(){t.removeListener(i,u),t.removeListener("error",c),o.cancel=wve}function u(...f){l(),s(f)}function c(f){l(),a(f)}n=l,t.on(i,u),t.on("error",c)});if(!n)throw new TypeError("Could not get `cancel()` function");return o.cancel=n,o}r.spread=e})(av||(av={}));f5.exports=av});var d5=g(rE=>{"use strict";Object.defineProperty(rE,"__esModule",{value:!0});function xve(r){return function(e,t){return new Promise((i,n)=>{r.call(this,e,t,(o,s)=>{o?n(o):i(s)})})}}rE.default=xve});var oE=g((iE,h5)=>{"use strict";var m5=iE&&iE.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},Dve=require("events"),Sve=m5(gt()),Eve=m5(d5()),Op=Sve.default("agent-base");function Cve(r){return Boolean(r)&&typeof r.addRequest=="function"}function nE(){let{stack:r}=new Error;return typeof r!="string"?!1:r.split(` +`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function lv(r,e){return new lv.Agent(r,e)}(function(r){class e extends Dve.EventEmitter{constructor(i,n){super();let o=n;typeof i=="function"?this.callback=i:i&&(o=i),this.timeout=null,o&&typeof o.timeout=="number"&&(this.timeout=o.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=Infinity,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:nE()?443:80}set defaultPort(i){this.explicitDefaultPort=i}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:nE()?"https:":"http:"}set protocol(i){this.explicitProtocol=i}callback(i,n,o){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(i,n){let o=Object.assign({},n);typeof o.secureEndpoint!="boolean"&&(o.secureEndpoint=nE()),o.host==null&&(o.host="localhost"),o.port==null&&(o.port=o.secureEndpoint?443:80),o.protocol==null&&(o.protocol=o.secureEndpoint?"https:":"http:"),o.host&&o.path&&delete o.path,delete o.agent,delete o.hostname,delete o._defaultAgent,delete o.defaultPort,delete o.createConnection,i._last=!0,i.shouldKeepAlive=!1;let s=!1,a=null,l=o.timeout||this.timeout,u=d=>{i._hadError||(i.emit("error",d),i._hadError=!0)},c=()=>{a=null,s=!0;let d=new Error(`A "socket" was not created for HTTP request before ${l}ms`);d.code="ETIMEOUT",u(d)},f=d=>{s||(a!==null&&(clearTimeout(a),a=null),u(d))},p=d=>{if(s)return;if(a!=null&&(clearTimeout(a),a=null),Cve(d)){Op("Callback returned another Agent instance %o",d.constructor.name),d.addRequest(i,o);return}if(d){d.once("free",()=>{this.freeSocket(d,o)}),i.onSocket(d);return}let h=new Error(`no Duplex stream was returned to agent-base for \`${i.method} ${i.path}\``);u(h)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Op("Converting legacy callback function to promise"),this.promisifiedCallback=Eve.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(a=setTimeout(c,l)),"port"in o&&typeof o.port!="number"&&(o.port=Number(o.port));try{Op("Resolving socket for %o request: %o",o.protocol,`${i.method} ${i.path}`),Promise.resolve(this.promisifiedCallback(i,o)).then(p,f)}catch(d){Promise.reject(d).catch(f)}}freeSocket(i,n){Op("Freeing socket %o %o",i.constructor.name,n),i.destroy()}destroy(){Op("Destroying agent %o",this.constructor.name)}}r.Agent=e,r.prototype=r.Agent.prototype})(lv||(lv={}));h5.exports=lv});var v5=g(ba=>{"use strict";var _ve=ba&&ba.__awaiter||function(r,e,t,i){function n(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function a(c){try{u(i.next(c))}catch(f){s(f)}}function l(c){try{u(i.throw(c))}catch(f){s(f)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((i=i.apply(r,e||[])).next())})},Lp=ba&&ba.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ba,"__esModule",{value:!0});var Pve=Lp(require("net")),Tve=Lp(require("tls")),sE=Lp(require("url")),Rve=Lp(gt()),kve=Lp(p5()),Ive=oE(),os=Rve.default("http-proxy-agent");function Fve(r){return typeof r=="string"?/^https:?$/i.test(r):!1}var g5=class extends Ive.Agent{constructor(e){let t;if(typeof e=="string"?t=sE.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");os("Creating new HttpProxyAgent instance: %o",t),super(t);let i=Object.assign({},t);this.secureProxy=t.secureProxy||Fve(i.protocol),i.host=i.hostname||i.host,typeof i.port=="string"&&(i.port=parseInt(i.port,10)),!i.port&&i.host&&(i.port=this.secureProxy?443:80),i.host&&i.path&&(delete i.path,delete i.pathname),this.proxy=i}callback(e,t){return _ve(this,void 0,void 0,function*(){let{proxy:i,secureProxy:n}=this,o=sE.default.parse(e.path);o.protocol||(o.protocol="http:"),o.hostname||(o.hostname=t.hostname||t.host||null),o.port==null&&typeof t.port&&(o.port=String(t.port)),o.port==="80"&&delete o.port,e.path=sE.default.format(o),i.auth&&e.setHeader("Proxy-Authorization",`Basic ${Buffer.from(i.auth).toString("base64")}`);let s;if(n?(os("Creating `tls.Socket`: %o",i),s=Tve.default.connect(i)):(os("Creating `net.Socket`: %o",i),s=Pve.default.connect(i)),e._header){let a,l;os("Regenerating stored HTTP header string for request"),e._header=null,e._implicitHeader(),e.output&&e.output.length>0?(os("Patching connection write() output buffer with updated header"),a=e.output[0],l=a.indexOf(`\r +\r +`)+4,e.output[0]=e._header+a.substring(l),os("Output buffer: %o",e.output)):e.outputData&&e.outputData.length>0&&(os("Patching connection write() output buffer with updated header"),a=e.outputData[0].data,l=a.indexOf(`\r +\r +`)+4,e.outputData[0].data=e._header+a.substring(l),os("Output buffer: %o",e.outputData[0].data))}return yield kve.default(s,"connect"),s})}};ba.default=g5});var b5=g((aE,y5)=>{"use strict";var Ave=aE&&aE.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},lE=Ave(v5());function uE(r){return new lE.default(r)}(function(r){r.HttpProxyAgent=lE.default,r.prototype=lE.default.prototype})(uE||(uE={}));y5.exports=uE});var w5=g(Mp=>{"use strict";var Ove=Mp&&Mp.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mp,"__esModule",{value:!0});var Lve=Ove(gt()),Np=Lve.default("https-proxy-agent:parse-proxy-response");function Mve(r){return new Promise((e,t)=>{let i=0,n=[];function o(){let f=r.read();f?c(f):r.once("readable",o)}function s(){r.removeListener("end",l),r.removeListener("error",u),r.removeListener("close",a),r.removeListener("readable",o)}function a(f){Np("onclose had error %o",f)}function l(){Np("onend")}function u(f){s(),Np("onerror %o",f),t(f)}function c(f){n.push(f),i+=f.length;let p=Buffer.concat(n,i);if(p.indexOf(`\r +\r +`)===-1){Np("have not received end of HTTP headers yet..."),o();return}let h=p.toString("ascii",0,p.indexOf(`\r +`)),m=+h.split(" ")[1];Np("got proxy server response: %o",h),e({statusCode:m,buffered:p})}r.on("error",u),r.on("close",a),r.on("end",l),o()})}Mp.default=Mve});var E5=g(wa=>{"use strict";var Nve=wa&&wa.__awaiter||function(r,e,t,i){function n(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function a(c){try{u(i.next(c))}catch(f){s(f)}}function l(c){try{u(i.throw(c))}catch(f){s(f)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((i=i.apply(r,e||[])).next())})},Eu=wa&&wa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(wa,"__esModule",{value:!0});var x5=Eu(require("net")),D5=Eu(require("tls")),qve=Eu(require("url")),$ve=Eu(require("assert")),Bve=Eu(gt()),jve=oE(),Uve=Eu(w5()),qp=Bve.default("https-proxy-agent:agent"),S5=class extends jve.Agent{constructor(e){let t;if(typeof e=="string"?t=qve.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");qp("creating new HttpsProxyAgent instance: %o",t),super(t);let i=Object.assign({},t);this.secureProxy=t.secureProxy||zve(i.protocol),i.host=i.hostname||i.host,typeof i.port=="string"&&(i.port=parseInt(i.port,10)),!i.port&&i.host&&(i.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in i)&&(i.ALPNProtocols=["http 1.1"]),i.host&&i.path&&(delete i.path,delete i.pathname),this.proxy=i}callback(e,t){return Nve(this,void 0,void 0,function*(){let{proxy:i,secureProxy:n}=this,o;n?(qp("Creating `tls.Socket`: %o",i),o=D5.default.connect(i)):(qp("Creating `net.Socket`: %o",i),o=x5.default.connect(i));let s=Object.assign({},i.headers),l=`CONNECT ${`${t.host}:${t.port}`} HTTP/1.1\r +`;i.auth&&(s["Proxy-Authorization"]=`Basic ${Buffer.from(i.auth).toString("base64")}`);let{host:u,port:c,secureEndpoint:f}=t;Hve(c,f)||(u+=`:${c}`),s.Host=u,s.Connection="close";for(let y of Object.keys(s))l+=`${y}: ${s[y]}\r +`;let p=Uve.default(o);o.write(`${l}\r +`);let{statusCode:d,buffered:h}=yield p;if(d===200){if(e.once("socket",Wve),t.secureEndpoint){let y=t.servername||t.host;if(!y)throw new Error('Could not determine "servername"');return qp("Upgrading socket connection to TLS"),D5.default.connect(Object.assign(Object.assign({},Gve(t,"host","hostname","path","port")),{socket:o,servername:y}))}return o}o.destroy();let m=new x5.default.Socket;return m.readable=!0,e.once("socket",y=>{qp("replaying proxy buffer for failed request"),$ve.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),m})}};wa.default=S5;function Wve(r){r.resume()}function Hve(r,e){return Boolean(!e&&r===80||e&&r===443)}function zve(r){return typeof r=="string"?/^https:?$/i.test(r):!1}function Gve(r,...e){let t={},i;for(i in r)e.includes(i)||(t[i]=r[i]);return t}});var _5=g((cE,C5)=>{"use strict";var Vve=cE&&cE.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},fE=Vve(E5());function pE(r){return new fE.default(r)}(function(r){r.HttpsProxyAgent=fE.default,r.prototype=fE.default.prototype})(pE||(pE={}));C5.exports=pE});var T5=g((pLe,P5)=>{"use strict";var Kve=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];P5.exports=(r,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(r).concat(Kve)),i={};for(let n of t)n in e||(i[n]={get(){let o=r[n];return typeof o=="function"?o.bind(r):o},set(o){r[n]=o},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),r.once("aborted",()=>{e.destroy(),e.emit("aborted")}),r.once("close",()=>{r.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var k5=g((dLe,R5)=>{"use strict";var{Transform:Jve,PassThrough:Yve}=require("stream"),dE=require("zlib"),Xve=T5();R5.exports=r=>{let e=(r.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return r;let t=e==="br";if(t&&typeof dE.createBrotliDecompress!="function")return r.destroy(new Error("Brotli is not supported on Node.js < 12")),r;let i=!0,n=new Jve({transform(a,l,u){i=!1,u(null,a)},flush(a){a()}}),o=new Yve({autoDestroy:!1,destroy(a,l){r.destroy(),l(a)}}),s=t?dE.createBrotliDecompress():dE.createUnzip();return s.once("error",a=>{if(i&&!r.readable){o.end();return}o.destroy(a)}),Xve(r,o),r.pipe(n).pipe(s).pipe(o),o}});var Uz=g(Uye=>{fo(Uye,{BaseLanguageClient:()=>yv,BasicList:()=>Mt,Buffer:()=>Ou.Buffer,CancellationToken:()=>ie.CancellationToken,CancellationTokenSource:()=>ie.CancellationTokenSource,ClientState:()=>be,CloseAction:()=>ro,CodeActionKind:()=>ie.CodeActionKind,CompletionItemKind:()=>ie.CompletionItemKind,CompletionTriggerKind:()=>ie.CompletionTriggerKind,ConfigurationTarget:()=>pt,Diagnostic:()=>ie.Diagnostic,DiagnosticSeverity:()=>ie.DiagnosticSeverity,DiagnosticTag:()=>ie.DiagnosticTag,Disposable:()=>ie.Disposable,Document:()=>Zm,DocumentHighlightKind:()=>ie.DocumentHighlightKind,Emitter:()=>ie.Emitter,ErrorAction:()=>Tu,Event:()=>ie.Event,ExtensionType:()=>Jr,FileChangeType:()=>ie.FileChangeType,FileSystemWatcher:()=>tg,FloatFactory:()=>mn,Highligher:()=>ss,InsertTextFormat:()=>ie.InsertTextFormat,LanguageClient:()=>Cv,Location:()=>ie.Location,LocationLink:()=>ie.LocationLink,MarkupKind:()=>ie.MarkupKind,MessageLevel:()=>gn,MessageTransports:()=>Hp,Mru:()=>Gl,Mutex:()=>ar,Neovim:()=>Ou.Neovim,NotificationType:()=>ie.NotificationType,NotificationType0:()=>ie.NotificationType0,NullLogger:()=>tH,PatternType:()=>Kr,Position:()=>ie.Position,ProgressType:()=>jz.ProgressType,ProposedFeatures:()=>_v,Range:()=>ie.Range,RequestType:()=>ie.RequestType,RequestType0:()=>ie.RequestType0,RevealOutputChannelOn:()=>ii,ServiceStat:()=>ye,SettingMonitor:()=>$H,SignatureHelpTriggerKind:()=>ie.SignatureHelpTriggerKind,SourceType:()=>Yr,State:()=>ni,SymbolKind:()=>ie.SymbolKind,TextDocumentFeature:()=>Ge,TextEdit:()=>ie.TextEdit,TransportKind:()=>Gt,Uri:()=>$,Watchman:()=>ta,Window:()=>Ou.Window,ansiparse:()=>Nf,commands:()=>me,concurrent:()=>vf,diagnosticManager:()=>St,disposeAll:()=>z,download:()=>Bp,events:()=>A,executable:()=>gf,extensions:()=>ge,fetch:()=>Cu,isRunning:()=>cq,languages:()=>U,listManager:()=>Kt,runCommand:()=>hn,services:()=>Vt,snippetManager:()=>Ft,sources:()=>Ze,wait:()=>He,watchFile:()=>Pl,window:()=>C,workspace:()=>b});var Ou=S(Lw()),ie=S(W()),jz=S(bi())});var t9=g(Kye=>{fo(Kye,{default:()=>Jye,regist:()=>Yye});var e9=S(W()),nHe=j()("source-around"),Nv=class extends Tn{constructor(){super({name:"around",filepath:__filename})}doComplete(e){let{bufnr:t,input:i}=e;if(i.length===0)return null;let n=b.getDocument(t);if(!n)return null;let o=n.words,s=n.getMoreWords();return o.push(...s),o=this.filterWords(o,e),Promise.resolve({items:o.map(a=>({word:a,menu:this.menu}))})}},Jye=Nv;function Yye(r){return r.set("around",new Nv),e9.Disposable.create(()=>{r.delete("around")})}});var i9=g(Xye=>{fo(Xye,{default:()=>Zye,regist:()=>Qye});var r9=S(W()),lHe=j()("source-buffer"),qv=class extends Tn{constructor(){super({name:"buffer",filepath:__filename})}get ignoreGitignore(){return this.getConfig("ignoreGitignore",!0)}getWords(e){let{ignoreGitignore:t}=this,i=[];return b.documents.forEach(n=>{if(n.bufnr!=e&&!(t&&n.isIgnored))for(let o of n.words)i.includes(o)||i.push(o)}),i}doComplete(e){let{bufnr:t,input:i}=e;if(i.length==0)return null;let n=this.getWords(t);return n=this.filterWords(n,e),Promise.resolve({items:n.map(o=>({word:o,menu:this.menu}))})}},Zye=qv;function Qye(r){return r.set("buffer",new qv),r9.Disposable.create(()=>{r.delete("buffer")})}});var a9=g(ebe=>{fo(ebe,{default:()=>ibe,regist:()=>nbe});var $v=S(require("fs")),n9=S(Qs()),oi=S(require("path")),o9=S(require("util")),s9=S(W()),tbe=j()("source-file"),rbe=/(?:\.{0,2}|~|\$HOME|([\w]+)|)\/(?:[\w.@()-]+\/)*(?:[\w.@()-])*$/,Bv=class extends Tn{constructor(){super({name:"file",filepath:__filename})}resolveEnvVariables(e){let t=e;return t=t.replace(/%([^%]+)%/g,(i,n)=>process.env[n]),t=t.replace(/\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/gi,(i,n,o)=>process.env[n||o]),t}getPathOption(e){let{line:t,colnr:i}=e,n=Rt(t,0,i-1);if(n=this.resolveEnvVariables(n),!n||n.endsWith("//"))return null;let o=n.match(rbe);if(o&&o.length){let s=b.expand(o[0]),a=o[0].match(/[^/]*$/)[0];return{pathstr:s,part:o[1],startcol:i-a.length-1,input:a}}return null}async getFileItem(e,t){let i=oi.default.join(e,t),n=await Ht(i);if(n){let o=n.isDirectory()?t+"/":t;return{word:t,abbr:o}}return null}filterFiles(e){let t=this.getConfig("ignoreHidden",!0),i=this.getConfig("ignorePatterns",[]);return e.filter(n=>{if(n==null||t&&n.startsWith("."))return!1;for(let o of i)if(n9.default(n,o,{dot:!0}))return!1;return!0})}async getItemsFromRoot(e,t){let i=[],n=e.endsWith("/")?e:oi.default.dirname(e),o=oi.default.isAbsolute(e)?n:oi.default.join(t,n);try{let s=await Ht(o);if(s&&s.isDirectory()){let a=await o9.default.promisify($v.default.readdir)(o);a=this.filterFiles(a);let l=await Promise.all(a.map(u=>this.getFileItem(o,u)));i=i.concat(l)}return i=i.filter(a=>a!=null),i}catch(s){return tbe.error("Error on list files:",s),i}}get trimSameExts(){return this.getConfig("trimSameExts",[])}async doComplete(e){let{col:t,filepath:i}=e,n=this.getPathOption(e);if(!n)return null;let{pathstr:o,part:s,startcol:a,input:l}=n;if(av.word[0]===y)),{items:h.map(v=>{let x=oi.default.extname(v.word);return v.word=m&&x===f?v.word.replace(f,""):v.word,{word:`${u}${v.word}`,abbr:`${u}${v.abbr}`,menu:this.menu}})}}},ibe=Bv;function nbe(r){return r.set("file",new Bv),s9.Disposable.create(()=>{r.delete("file")})}});var so=g((R9e,R9)=>{"use strict";var cbe=un();R9.exports=cbe.call(Function.call,Object.prototype.hasOwnProperty)});var Vv=g((k9e,k9)=>{"use strict";var we,id=SyntaxError,fbe=Function,Bu=TypeError,ZC=function(r){try{return Function('"use strict"; return ('+r+").constructor;")()}catch(e){}},Pa=Object.getOwnPropertyDescriptor;if(Pa)try{Pa({},"")}catch(r){Pa=null}var QC=function(){throw new Bu},pbe=Pa?function(){try{return arguments.callee,QC}catch(r){try{return Pa(arguments,"callee").get}catch(e){return QC}}}():QC,ju=Li()(),fs=Object.getPrototypeOf||function(r){return r.__proto__},e_=ZC("async function* () {}"),t_=e_?e_.prototype:we,I9=t_?t_.prototype:we,dbe=typeof Uint8Array=="undefined"?we:fs(Uint8Array),nd={"%AggregateError%":typeof AggregateError=="undefined"?we:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?we:ArrayBuffer,"%ArrayIteratorPrototype%":ju?fs([][Symbol.iterator]()):we,"%AsyncFromSyncIteratorPrototype%":we,"%AsyncFunction%":ZC("async function () {}"),"%AsyncGenerator%":t_,"%AsyncGeneratorFunction%":e_,"%AsyncIteratorPrototype%":I9?fs(I9):we,"%Atomics%":typeof Atomics=="undefined"?we:Atomics,"%BigInt%":typeof BigInt=="undefined"?we:BigInt,"%Boolean%":Boolean,"%DataView%":typeof DataView=="undefined"?we:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array=="undefined"?we:Float32Array,"%Float64Array%":typeof Float64Array=="undefined"?we:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry=="undefined"?we:FinalizationRegistry,"%Function%":fbe,"%GeneratorFunction%":ZC("function* () {}"),"%Int8Array%":typeof Int8Array=="undefined"?we:Int8Array,"%Int16Array%":typeof Int16Array=="undefined"?we:Int16Array,"%Int32Array%":typeof Int32Array=="undefined"?we:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":ju?fs(fs([][Symbol.iterator]())):we,"%JSON%":typeof JSON=="object"?JSON:we,"%Map%":typeof Map=="undefined"?we:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!ju?we:fs(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?we:Promise,"%Proxy%":typeof Proxy=="undefined"?we:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect=="undefined"?we:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set=="undefined"?we:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!ju?we:fs(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?we:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":ju?fs(""[Symbol.iterator]()):we,"%Symbol%":ju?Symbol:we,"%SyntaxError%":id,"%ThrowTypeError%":pbe,"%TypedArray%":dbe,"%TypeError%":Bu,"%Uint8Array%":typeof Uint8Array=="undefined"?we:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?we:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array=="undefined"?we:Uint16Array,"%Uint32Array%":typeof Uint32Array=="undefined"?we:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap=="undefined"?we:WeakMap,"%WeakRef%":typeof WeakRef=="undefined"?we:WeakRef,"%WeakSet%":typeof WeakSet=="undefined"?we:WeakSet},F9={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Hv=un(),zv=so(),hbe=Hv.call(Function.call,Array.prototype.concat),mbe=Hv.call(Function.apply,Array.prototype.splice),A9=Hv.call(Function.call,String.prototype.replace),Gv=Hv.call(Function.call,String.prototype.slice),gbe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,vbe=/\\(\\)?/g,ybe=function(e){var t=Gv(e,0,1),i=Gv(e,-1);if(t==="%"&&i!=="%")throw new id("invalid intrinsic syntax, expected closing `%`");if(i==="%"&&t!=="%")throw new id("invalid intrinsic syntax, expected opening `%`");var n=[];return A9(e,gbe,function(o,s,a,l){n[n.length]=a?A9(l,vbe,"$1"):s||o}),n},bbe=function(e,t){var i=e,n;if(zv(F9,i)&&(n=F9[i],i="%"+n[0]+"%"),zv(nd,i)){var o=nd[i];if(typeof o=="undefined"&&!t)throw new Bu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:i,value:o}}throw new id("intrinsic "+e+" does not exist!")};k9.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new Bu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new Bu('"allowMissing" argument must be a boolean');var i=ybe(e),n=i.length>0?i[0]:"",o=bbe("%"+n+"%",t),s=o.name,a=o.value,l=!1,u=o.alias;u&&(n=u[0],mbe(i,hbe([0,1],u)));for(var c=1,f=!0;c=i.length){var m=Pa(a,p);f=!!m,f&&"get"in m&&!("originalValue"in m.get)?a=m.get:a=a[p]}else f=zv(a,p),a=a[p];f&&!l&&(nd[s]=a)}}return a}});var i_=g((I9e,Kv)=>{"use strict";var r_=un(),Jv=Vv(),O9=Jv("%Function.prototype.apply%"),L9=Jv("%Function.prototype.call%"),M9=Jv("%Reflect.apply%",!0)||r_.call(L9,O9),od=Jv("%Object.defineProperty%",!0);if(od)try{od({},"a",{value:1})}catch(r){od=null}Kv.exports=function(){return M9(r_,L9,arguments)};var N9=function(){return M9(r_,O9,arguments)};od?od(Kv.exports,"apply",{value:N9}):Kv.exports.apply=N9});var Ae=g((F9e,q9)=>{"use strict";var De,$9=SyntaxError,wbe=Function,Uu=TypeError,n_=function(r){try{return Function('"use strict"; return ('+r+").constructor;")()}catch(e){}},Ta=Object.getOwnPropertyDescriptor;if(Ta)try{Ta({},"")}catch(r){Ta=null}var o_=function(){throw new Uu},xbe=Ta?function(){try{return arguments.callee,o_}catch(r){try{return Ta(arguments,"callee").get}catch(e){return o_}}}():o_,Wu=Li()(),ps=Object.getPrototypeOf||function(r){return r.__proto__},s_=n_("async function* () {}"),a_=s_?s_.prototype:De,B9=a_?a_.prototype:De,Dbe=typeof Uint8Array=="undefined"?De:ps(Uint8Array),sd={"%AggregateError%":typeof AggregateError=="undefined"?De:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?De:ArrayBuffer,"%ArrayIteratorPrototype%":Wu?ps([][Symbol.iterator]()):De,"%AsyncFromSyncIteratorPrototype%":De,"%AsyncFunction%":n_("async function () {}"),"%AsyncGenerator%":a_,"%AsyncGeneratorFunction%":s_,"%AsyncIteratorPrototype%":B9?ps(B9):De,"%Atomics%":typeof Atomics=="undefined"?De:Atomics,"%BigInt%":typeof BigInt=="undefined"?De:BigInt,"%Boolean%":Boolean,"%DataView%":typeof DataView=="undefined"?De:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array=="undefined"?De:Float32Array,"%Float64Array%":typeof Float64Array=="undefined"?De:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry=="undefined"?De:FinalizationRegistry,"%Function%":wbe,"%GeneratorFunction%":n_("function* () {}"),"%Int8Array%":typeof Int8Array=="undefined"?De:Int8Array,"%Int16Array%":typeof Int16Array=="undefined"?De:Int16Array,"%Int32Array%":typeof Int32Array=="undefined"?De:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Wu?ps(ps([][Symbol.iterator]())):De,"%JSON%":typeof JSON=="object"?JSON:De,"%Map%":typeof Map=="undefined"?De:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!Wu?De:ps(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?De:Promise,"%Proxy%":typeof Proxy=="undefined"?De:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect=="undefined"?De:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set=="undefined"?De:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!Wu?De:ps(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?De:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Wu?ps(""[Symbol.iterator]()):De,"%Symbol%":Wu?Symbol:De,"%SyntaxError%":$9,"%ThrowTypeError%":xbe,"%TypedArray%":Dbe,"%TypeError%":Uu,"%Uint8Array%":typeof Uint8Array=="undefined"?De:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?De:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array=="undefined"?De:Uint16Array,"%Uint32Array%":typeof Uint32Array=="undefined"?De:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap=="undefined"?De:WeakMap,"%WeakRef%":typeof WeakRef=="undefined"?De:WeakRef,"%WeakSet%":typeof WeakSet=="undefined"?De:WeakSet},j9={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},l_=un(),Yv=so(),Sbe=l_.call(Function.call,Array.prototype.concat),Ebe=l_.call(Function.apply,Array.prototype.splice),U9=l_.call(Function.call,String.prototype.replace),Cbe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,_be=/\\(\\)?/g,Pbe=function(e){var t=[];return U9(e,Cbe,function(i,n,o,s){t[t.length]=o?U9(s,_be,"$1"):n||i}),t},Tbe=function(e,t){var i=e,n;if(Yv(j9,i)&&(n=j9[i],i="%"+n[0]+"%"),Yv(sd,i)){var o=sd[i];if(typeof o=="undefined"&&!t)throw new Uu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:i,value:o}}throw new $9("intrinsic "+e+" does not exist!")};q9.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new Uu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new Uu('"allowMissing" argument must be a boolean');var i=Pbe(e),n=i.length>0?i[0]:"",o=Tbe("%"+n+"%",t),s=o.name,a=o.value,l=!1,u=o.alias;u&&(n=u[0],Ebe(i,Sbe([0,1],u)));for(var c=1,f=!0;c=i.length){var d=Ta(a,p);if(f=!!d,!t&&!(p in a))throw new Uu("base intrinsic for "+e+" exists, but the property is not available.");f&&"get"in d&&!("originalValue"in d.get)?a=d.get:a=a[p]}else f=Yv(a,p),a=a[p];f&&!l&&(sd[s]=a)}}return a}});var c_=g((A9e,Xv)=>{"use strict";var u_=un(),Zv=Ae(),W9=Zv("%Function.prototype.apply%"),H9=Zv("%Function.prototype.call%"),z9=Zv("%Reflect.apply%",!0)||u_.call(H9,W9),ad=Zv("%Object.defineProperty%",!0);if(ad)try{ad({},"a",{value:1})}catch(r){ad=null}Xv.exports=function(){return z9(u_,H9,arguments)};var G9=function(){return z9(u_,W9,arguments)};ad?ad(Xv.exports,"apply",{value:G9}):Xv.exports.apply=G9});var Ra=g((O9e,V9)=>{"use strict";var K9=Ae(),J9=c_(),Rbe=J9(K9("String.prototype.indexOf"));V9.exports=function(e,t){var i=K9(e,!!t);return typeof i=="function"&&Rbe(e,".prototype.")?J9(i):i}});var f_=g((L9e,Y9)=>{"use strict";var kbe=Ae(),Ibe=Ra(),Fbe=kbe("%Reflect.apply%",!0)||Ibe("%Function.prototype.apply%");Y9.exports=function(e,t){var i=arguments.length>2?arguments[2]:[];return Fbe(e,t,i)}});var Z9=g((M9e,X9)=>{X9.exports=require("util").inspect});var w_=g((N9e,Q9)=>{var p_=typeof Map=="function"&&Map.prototype,d_=Object.getOwnPropertyDescriptor&&p_?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Qv=p_&&d_&&typeof d_.get=="function"?d_.get:null,Abe=p_&&Map.prototype.forEach,h_=typeof Set=="function"&&Set.prototype,m_=Object.getOwnPropertyDescriptor&&h_?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,ey=h_&&m_&&typeof m_.get=="function"?m_.get:null,Obe=h_&&Set.prototype.forEach,Lbe=typeof WeakMap=="function"&&WeakMap.prototype,ld=Lbe?WeakMap.prototype.has:null,Mbe=typeof WeakSet=="function"&&WeakSet.prototype,ud=Mbe?WeakSet.prototype.has:null,Nbe=Boolean.prototype.valueOf,qbe=Object.prototype.toString,$be=Function.prototype.toString,Bbe=String.prototype.match,jbe=typeof BigInt=="function"?BigInt.prototype.valueOf:null,e7=Object.getOwnPropertySymbols,Ube=typeof Symbol=="function"?Symbol.prototype.toString:null,Wbe=Object.prototype.propertyIsEnumerable,g_=Z9().custom,v_=g_&&t7(g_)?g_:null;Q9.exports=function r(e,t,i,n){var o=t||{};if(ka(o,"quoteStyle")&&o.quoteStyle!=="single"&&o.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(ka(o,"maxStringLength")&&(typeof o.maxStringLength=="number"?o.maxStringLength<0&&o.maxStringLength!==Infinity:o.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var s=ka(o,"customInspect")?o.customInspect:!0;if(typeof s!="boolean")throw new TypeError('option "customInspect", if provided, must be `true` or `false`');if(ka(o,"indent")&&o.indent!==null&&o.indent!==" "&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(typeof e=="undefined")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return n7(e,o);if(typeof e=="number")return e===0?Infinity/e>0?"0":"-0":String(e);if(typeof e=="bigint")return String(e)+"n";var a=typeof o.depth=="undefined"?5:o.depth;if(typeof i=="undefined"&&(i=0),i>=a&&a>0&&typeof e=="object")return y_(e)?"[Array]":"[Object]";var l=owe(o,i);if(typeof n=="undefined")n=[];else if(i7(n,e)>=0)return"[Circular]";function u(P,k,_){if(k&&(n=n.slice(),n.push(k)),_){var O={depth:o.depth};return ka(o,"quoteStyle")&&(O.quoteStyle=o.quoteStyle),r(P,O,i+1,n)}return r(P,o,i+1,n)}if(typeof e=="function"){var c=Zbe(e),f=ty(e,u);return"[Function"+(c?": "+c:" (anonymous)")+"]"+(f.length>0?" { "+f.join(", ")+" }":"")}if(t7(e)){var p=Ube.call(e);return typeof e=="object"?cd(p):p}if(iwe(e)){for(var d="<"+String(e.nodeName).toLowerCase(),h=e.attributes||[],m=0;m",d}if(y_(e)){if(e.length===0)return"[]";var y=ty(e,u);return l&&!nwe(y)?"["+b_(y,l)+"]":"[ "+y.join(", ")+" ]"}if(Vbe(e)){var v=ty(e,u);return v.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+v.join(", ")+" }"}if(typeof e=="object"&&s){if(v_&&typeof e[v_]=="function")return e[v_]();if(typeof e.inspect=="function")return e.inspect()}if(Qbe(e)){var x=[];return Abe.call(e,function(P,k){x.push(u(k,e,!0)+" => "+u(P,e))}),s7("Map",Qv.call(e),x,l)}if(twe(e)){var w=[];return Obe.call(e,function(P){w.push(u(P,e))}),s7("Set",ey.call(e),w,l)}if(ewe(e))return o7("WeakMap");if(rwe(e))return o7("WeakSet");if(Jbe(e))return cd(u(Number(e)));if(Ybe(e))return cd(u(jbe.call(e)));if(Xbe(e))return cd(Nbe.call(e));if(Kbe(e))return cd(u(String(e)));if(!zbe(e)&&!Gbe(e)){var E=ty(e,u);return E.length===0?"{}":l?"{"+b_(E,l)+"}":"{ "+E.join(", ")+" }"}return String(e)};function r7(r,e,t){var i=(t.quoteStyle||e)==="double"?'"':"'";return i+r+i}function Hbe(r){return String(r).replace(/"/g,""")}function y_(r){return ao(r)==="[object Array]"}function zbe(r){return ao(r)==="[object Date]"}function Gbe(r){return ao(r)==="[object RegExp]"}function Vbe(r){return ao(r)==="[object Error]"}function t7(r){return ao(r)==="[object Symbol]"}function Kbe(r){return ao(r)==="[object String]"}function Jbe(r){return ao(r)==="[object Number]"}function Ybe(r){return ao(r)==="[object BigInt]"}function Xbe(r){return ao(r)==="[object Boolean]"}var swe=Object.prototype.hasOwnProperty||function(r){return r in this};function ka(r,e){return swe.call(r,e)}function ao(r){return qbe.call(r)}function Zbe(r){if(r.name)return r.name;var e=Bbe.call($be.call(r),/^function\s*([\w$]+)/);return e?e[1]:null}function i7(r,e){if(r.indexOf)return r.indexOf(e);for(var t=0,i=r.length;te.maxStringLength){var t=r.length-e.maxStringLength,i="... "+t+" more character"+(t>1?"s":"");return n7(r.slice(0,e.maxStringLength),e)+i}var n=r.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,awe);return r7(n,"single",e)}function awe(r){var e=r.charCodeAt(0),t={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return t?"\\"+t:"\\x"+(e<16?"0":"")+e.toString(16).toUpperCase()}function cd(r){return"Object("+r+")"}function o7(r){return r+" { ? }"}function s7(r,e,t,i){var n=i?b_(t,i):t.join(", ");return r+" ("+e+") {"+n+"}"}function nwe(r){for(var e=0;e=0)return!1;return!0}function owe(r,e){var t;if(r.indent===" ")t=" ";else if(typeof r.indent=="number"&&r.indent>0)t=Array(r.indent+1).join(" ");else return null;return{base:t,prev:Array(e+1).join(t)}}function b_(r,e){if(r.length===0)return"";var t=` +`+e.prev+e.base;return t+r.join(","+t)+` +`+e.prev}function ty(r,e){var t=y_(r),i=[];if(t){i.length=r.length;for(var n=0;n{"use strict";a7.exports=function(e){return typeof e=="string"||typeof e=="symbol"}});var u7=g(($9e,l7)=>{"use strict";l7.exports=function(e){if(e===null)return"Null";if(typeof e=="undefined")return"Undefined";if(typeof e=="function"||typeof e=="object")return"Object";if(typeof e=="number")return"Number";if(typeof e=="boolean")return"Boolean";if(typeof e=="string")return"String"}});var pr=g((B9e,c7)=>{"use strict";var lwe=u7();c7.exports=function(e){return typeof e=="symbol"?"Symbol":typeof e=="bigint"?"BigInt":lwe(e)}});var fd=g((j9e,f7)=>{"use strict";var uwe=Ae(),p7=uwe("%TypeError%"),cwe=w_(),fwe=Hu(),pwe=pr();f7.exports=function(e,t){if(pwe(e)!=="Object")throw new p7("Assertion failed: Type(O) is not Object");if(!fwe(t))throw new p7("Assertion failed: IsPropertyKey(P) is not true, got "+cwe(t));return e[t]}});var h7=g((U9e,d7)=>{"use strict";var dwe=Ae(),hwe=dwe("%TypeError%");d7.exports=function(e,t){if(e==null)throw new hwe(t||"Cannot call method on "+e);return e}});var x_=g((W9e,m7)=>{"use strict";m7.exports=h7()});var v7=g((H9e,g7)=>{"use strict";var mwe=Ae(),gwe=mwe("%Object%"),vwe=x_();g7.exports=function(e){return vwe(e),gwe(e)}});var b7=g((z9e,y7)=>{"use strict";var ywe=Ae(),bwe=ywe("%TypeError%"),wwe=Hu(),xwe=v7();y7.exports=function(e,t){if(!wwe(t))throw new bwe("Assertion failed: IsPropertyKey(P) is not true");var i=xwe(e);return i[t]}});var D7=g((G9e,w7)=>{"use strict";var x7=Function.prototype.toString,zu=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,D_,ry;if(typeof zu=="function"&&typeof Object.defineProperty=="function")try{D_=Object.defineProperty({},"length",{get:function(){throw ry}}),ry={},zu(function(){throw 42},null,D_)}catch(r){r!==ry&&(zu=null)}else zu=null;var Dwe=/^\s*class\b/,S_=function(e){try{var t=x7.call(e);return Dwe.test(t)}catch(i){return!1}},Swe=function(e){try{return S_(e)?!1:(x7.call(e),!0)}catch(t){return!1}},Ewe=Object.prototype.toString,Cwe="[object Function]",_we="[object GeneratorFunction]",Pwe=typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol";w7.exports=zu?function(e){if(!e||typeof e!="function"&&typeof e!="object")return!1;if(typeof e=="function"&&!e.prototype)return!0;try{zu(e,null,D_)}catch(t){if(t!==ry)return!1}return!S_(e)}:function(e){if(!e||typeof e!="function"&&typeof e!="object")return!1;if(typeof e=="function"&&!e.prototype)return!0;if(Pwe)return Swe(e);if(S_(e))return!1;var t=Ewe.call(e);return t===Cwe||t===_we}});var iy=g((V9e,S7)=>{"use strict";S7.exports=D7()});var _7=g((K9e,E7)=>{"use strict";var Twe=Ae(),C7=Twe("%TypeError%"),Rwe=b7(),kwe=iy(),Iwe=Hu();E7.exports=function(e,t){if(!Iwe(t))throw new C7("Assertion failed: IsPropertyKey(P) is not true");var i=Rwe(e,t);if(i!=null){if(!kwe(i))throw new C7(t+"is not a function");return i}}});var I7=g((J9e,P7)=>{"use strict";var Fwe=Li()(),T7=Fwe&&typeof Symbol.toStringTag=="symbol",R7,k7,E_,C_;T7&&(R7=Function.call.bind(Object.prototype.hasOwnProperty),k7=Function.call.bind(RegExp.prototype.exec),E_={},ny=function(){throw E_},C_={toString:ny,valueOf:ny},typeof Symbol.toPrimitive=="symbol"&&(C_[Symbol.toPrimitive]=ny));var ny,Awe=Object.prototype.toString,Owe=Object.getOwnPropertyDescriptor,Lwe="[object RegExp]";P7.exports=T7?function(e){if(!e||typeof e!="object")return!1;var t=Owe(e,"lastIndex"),i=t&&R7(t,"value");if(!i)return!1;try{k7(e,C_)}catch(n){return n===E_}}:function(e){return!e||typeof e!="object"&&typeof e!="function"?!1:Awe.call(e)===Lwe}});var __=g((Y9e,F7)=>{"use strict";F7.exports=function(e){return!!e}});var L7=g((X9e,A7)=>{"use strict";var Mwe=Ae(),O7=Mwe("%Symbol.match%",!0),Nwe=I7(),qwe=__();A7.exports=function(e){if(!e||typeof e!="object")return!1;if(O7){var t=e[O7];if(typeof t!="undefined")return qwe(t)}return Nwe(e)}});var oy=g((Z9e,M7)=>{"use strict";var N7=Ae(),$we=N7("%String%"),Bwe=N7("%TypeError%");M7.exports=function(e){if(typeof e=="symbol")throw new Bwe("Cannot convert a Symbol value to a string");return $we(e)}});var P_=g((Q9e,q7)=>{"use strict";var $7=Vv(),B7=i_(),jwe=B7($7("String.prototype.indexOf"));q7.exports=function(e,t){var i=$7(e,!!t);return typeof i=="function"&&jwe(e,".prototype.")>-1?B7(i):i}});var L_=g((e7e,j7)=>{"use strict";var Z,pd=TypeError,Ia=Object.getOwnPropertyDescriptor;if(Ia)try{Ia({},"")}catch(r){Ia=null}var T_=function(){throw new pd},Uwe=Ia?function(){try{return arguments.callee,T_}catch(r){try{return Ia(arguments,"callee").get}catch(e){return T_}}}():T_,ds=Li()(),on=Object.getPrototypeOf||function(r){return r.__proto__},sy,R_=sy?on(sy):Z,U7,k_=U7?U7.constructor:Z,dd,I_=dd?on(dd):Z,F_=dd?dd():Z,A_=typeof Uint8Array=="undefined"?Z:on(Uint8Array),O_={"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?Z:ArrayBuffer,"%ArrayBufferPrototype%":typeof ArrayBuffer=="undefined"?Z:ArrayBuffer.prototype,"%ArrayIteratorPrototype%":ds?on([][Symbol.iterator]()):Z,"%ArrayPrototype%":Array.prototype,"%ArrayProto_entries%":Array.prototype.entries,"%ArrayProto_forEach%":Array.prototype.forEach,"%ArrayProto_keys%":Array.prototype.keys,"%ArrayProto_values%":Array.prototype.values,"%AsyncFromSyncIteratorPrototype%":Z,"%AsyncFunction%":k_,"%AsyncFunctionPrototype%":k_?k_.prototype:Z,"%AsyncGenerator%":dd?on(F_):Z,"%AsyncGeneratorFunction%":I_,"%AsyncGeneratorPrototype%":I_?I_.prototype:Z,"%AsyncIteratorPrototype%":F_&&ds&&Symbol.asyncIterator?F_[Symbol.asyncIterator]():Z,"%Atomics%":typeof Atomics=="undefined"?Z:Atomics,"%Boolean%":Boolean,"%BooleanPrototype%":Boolean.prototype,"%DataView%":typeof DataView=="undefined"?Z:DataView,"%DataViewPrototype%":typeof DataView=="undefined"?Z:DataView.prototype,"%Date%":Date,"%DatePrototype%":Date.prototype,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%ErrorPrototype%":Error.prototype,"%eval%":eval,"%EvalError%":EvalError,"%EvalErrorPrototype%":EvalError.prototype,"%Float32Array%":typeof Float32Array=="undefined"?Z:Float32Array,"%Float32ArrayPrototype%":typeof Float32Array=="undefined"?Z:Float32Array.prototype,"%Float64Array%":typeof Float64Array=="undefined"?Z:Float64Array,"%Float64ArrayPrototype%":typeof Float64Array=="undefined"?Z:Float64Array.prototype,"%Function%":Function,"%FunctionPrototype%":Function.prototype,"%Generator%":sy?on(sy()):Z,"%GeneratorFunction%":R_,"%GeneratorPrototype%":R_?R_.prototype:Z,"%Int8Array%":typeof Int8Array=="undefined"?Z:Int8Array,"%Int8ArrayPrototype%":typeof Int8Array=="undefined"?Z:Int8Array.prototype,"%Int16Array%":typeof Int16Array=="undefined"?Z:Int16Array,"%Int16ArrayPrototype%":typeof Int16Array=="undefined"?Z:Int8Array.prototype,"%Int32Array%":typeof Int32Array=="undefined"?Z:Int32Array,"%Int32ArrayPrototype%":typeof Int32Array=="undefined"?Z:Int32Array.prototype,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":ds?on(on([][Symbol.iterator]())):Z,"%JSON%":typeof JSON=="object"?JSON:Z,"%JSONParse%":typeof JSON=="object"?JSON.parse:Z,"%Map%":typeof Map=="undefined"?Z:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!ds?Z:on(new Map()[Symbol.iterator]()),"%MapPrototype%":typeof Map=="undefined"?Z:Map.prototype,"%Math%":Math,"%Number%":Number,"%NumberPrototype%":Number.prototype,"%Object%":Object,"%ObjectPrototype%":Object.prototype,"%ObjProto_toString%":Object.prototype.toString,"%ObjProto_valueOf%":Object.prototype.valueOf,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?Z:Promise,"%PromisePrototype%":typeof Promise=="undefined"?Z:Promise.prototype,"%PromiseProto_then%":typeof Promise=="undefined"?Z:Promise.prototype.then,"%Promise_all%":typeof Promise=="undefined"?Z:Promise.all,"%Promise_reject%":typeof Promise=="undefined"?Z:Promise.reject,"%Promise_resolve%":typeof Promise=="undefined"?Z:Promise.resolve,"%Proxy%":typeof Proxy=="undefined"?Z:Proxy,"%RangeError%":RangeError,"%RangeErrorPrototype%":RangeError.prototype,"%ReferenceError%":ReferenceError,"%ReferenceErrorPrototype%":ReferenceError.prototype,"%Reflect%":typeof Reflect=="undefined"?Z:Reflect,"%RegExp%":RegExp,"%RegExpPrototype%":RegExp.prototype,"%Set%":typeof Set=="undefined"?Z:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!ds?Z:on(new Set()[Symbol.iterator]()),"%SetPrototype%":typeof Set=="undefined"?Z:Set.prototype,"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?Z:SharedArrayBuffer,"%SharedArrayBufferPrototype%":typeof SharedArrayBuffer=="undefined"?Z:SharedArrayBuffer.prototype,"%String%":String,"%StringIteratorPrototype%":ds?on(""[Symbol.iterator]()):Z,"%StringPrototype%":String.prototype,"%Symbol%":ds?Symbol:Z,"%SymbolPrototype%":ds?Symbol.prototype:Z,"%SyntaxError%":SyntaxError,"%SyntaxErrorPrototype%":SyntaxError.prototype,"%ThrowTypeError%":Uwe,"%TypedArray%":A_,"%TypedArrayPrototype%":A_?A_.prototype:Z,"%TypeError%":pd,"%TypeErrorPrototype%":pd.prototype,"%Uint8Array%":typeof Uint8Array=="undefined"?Z:Uint8Array,"%Uint8ArrayPrototype%":typeof Uint8Array=="undefined"?Z:Uint8Array.prototype,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?Z:Uint8ClampedArray,"%Uint8ClampedArrayPrototype%":typeof Uint8ClampedArray=="undefined"?Z:Uint8ClampedArray.prototype,"%Uint16Array%":typeof Uint16Array=="undefined"?Z:Uint16Array,"%Uint16ArrayPrototype%":typeof Uint16Array=="undefined"?Z:Uint16Array.prototype,"%Uint32Array%":typeof Uint32Array=="undefined"?Z:Uint32Array,"%Uint32ArrayPrototype%":typeof Uint32Array=="undefined"?Z:Uint32Array.prototype,"%URIError%":URIError,"%URIErrorPrototype%":URIError.prototype,"%WeakMap%":typeof WeakMap=="undefined"?Z:WeakMap,"%WeakMapPrototype%":typeof WeakMap=="undefined"?Z:WeakMap.prototype,"%WeakSet%":typeof WeakSet=="undefined"?Z:WeakSet,"%WeakSetPrototype%":typeof WeakSet=="undefined"?Z:WeakSet.prototype},Wwe=un(),W7=Wwe.call(Function.call,String.prototype.replace),Hwe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,zwe=/\\(\\)?/g,Gwe=function(e){var t=[];return W7(e,Hwe,function(i,n,o,s){t[t.length]=o?W7(s,zwe,"$1"):n||i}),t},Vwe=function(e,t){if(!(e in O_))throw new SyntaxError("intrinsic "+e+" does not exist!");if(typeof O_[e]=="undefined"&&!t)throw new pd("intrinsic "+e+" exists, but is not available. Please file an issue!");return O_[e]};j7.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new TypeError('"allowMissing" argument must be a boolean');for(var i=Gwe(e),n=Vwe("%"+(i.length>0?i[0]:"")+"%",t),o=1;o=i.length){var s=Ia(n,i[o]);if(!t&&!(i[o]in n))throw new pd("base intrinsic for "+e+" exists, but the property is not available.");n=s&&"get"in s&&!("originalValue"in s.get)?s.get:n[i[o]]}else n=n[i[o]];return n}});var K7=g((t7e,ay)=>{"use strict";var M_=un(),ly=L_(),H7=ly("%Function.prototype.apply%"),z7=ly("%Function.prototype.call%"),G7=ly("%Reflect.apply%",!0)||M_.call(z7,H7),hd=ly("%Object.defineProperty%",!0);if(hd)try{hd({},"a",{value:1})}catch(r){hd=null}ay.exports=function(){return G7(M_,z7,arguments)};var V7=function(){return G7(M_,H7,arguments)};hd?hd(ay.exports,"apply",{value:V7}):ay.exports.apply=V7});var N_=g((r7e,J7)=>{"use strict";var Kwe=Object,Jwe=TypeError;J7.exports=function(){if(this!=null&&this!==Kwe(this))throw new Jwe("RegExp.prototype.flags getter called on non-object");var e="";return this.global&&(e+="g"),this.ignoreCase&&(e+="i"),this.multiline&&(e+="m"),this.dotAll&&(e+="s"),this.unicode&&(e+="u"),this.sticky&&(e+="y"),e}});var q_=g((i7e,Y7)=>{"use strict";var Ywe=N_(),Xwe=Fn().supportsDescriptors,Zwe=Object.getOwnPropertyDescriptor,Qwe=TypeError;Y7.exports=function(){if(!Xwe)throw new Qwe("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors");if(/a/mig.flags==="gim"){var e=Zwe(RegExp.prototype,"flags");if(e&&typeof e.get=="function"&&typeof/a/.dotAll=="boolean")return e.get}return Ywe}});var Q7=g((n7e,X7)=>{"use strict";var exe=Fn().supportsDescriptors,txe=q_(),rxe=Object.getOwnPropertyDescriptor,ixe=Object.defineProperty,nxe=TypeError,Z7=Object.getPrototypeOf,oxe=/a/;X7.exports=function(){if(!exe||!Z7)throw new nxe("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors");var e=txe(),t=Z7(oxe),i=rxe(t,"flags");return(!i||i.get!==e)&&ixe(t,"flags",{configurable:!0,enumerable:!1,get:e}),e}});var $_=g((o7e,eG)=>{"use strict";var sxe=Fn(),axe=K7(),tG=N_(),lxe=q_(),uxe=Q7(),rG=axe(tG);sxe(rG,{getPolyfill:lxe,implementation:tG,shim:uxe});eG.exports=rG});var uy=g((s7e,iG)=>{"use strict";iG.exports=Number.isNaN||function(e){return e!==e}});var B_=g((a7e,nG)=>{"use strict";var oG=uy();nG.exports=function(e,t){return e===t?e===0?1/e==1/t:!0:oG(e)&&oG(t)}});var j_=g((l7e,sG)=>{"use strict";var cxe=Ae(),cy=cxe("%TypeError%"),fxe=Hu(),aG=B_(),lG=pr(),uG=function(){try{return delete[].length,!0}catch(r){return!1}}();sG.exports=function(e,t,i,n){if(lG(e)!=="Object")throw new cy("Assertion failed: `O` must be an Object");if(!fxe(t))throw new cy("Assertion failed: `P` must be a Property Key");if(lG(n)!=="Boolean")throw new cy("Assertion failed: `Throw` must be a Boolean");if(n){if(e[t]=i,uG&&!aG(e[t],i))throw new cy("Attempted to assign to readonly property.");return!0}else try{return e[t]=i,uG?aG(e[t],i):!0}catch(o){return!1}}});var fG=g((u7e,cG)=>{"use strict";var pxe=Ae(),dxe=so(),hxe=pxe("%TypeError%");cG.exports=function(e,t){if(e.Type(t)!=="Object")return!1;var i={"[[Configurable]]":!0,"[[Enumerable]]":!0,"[[Get]]":!0,"[[Set]]":!0,"[[Value]]":!0,"[[Writable]]":!0};for(var n in t)if(dxe(t,n)&&!i[n])return!1;if(e.IsDataDescriptor(t)&&e.IsAccessorDescriptor(t))throw new hxe("Property Descriptors may not be both accessor and data descriptors");return!0}});var dG=g((c7e,pG)=>{"use strict";var mxe=Ae(),md=mxe("%Object.defineProperty%",!0);if(md)try{md({},"a",{value:1})}catch(r){md=null}var gxe=Ra(),vxe=gxe("Object.prototype.propertyIsEnumerable");pG.exports=function(e,t,i,n,o,s){if(!md){if(!e(s)||!s["[[Configurable]]"]||!s["[[Writable]]"]||o in n&&vxe(n,o)!==!!s["[[Enumerable]]"])return!1;var a=s["[[Value]]"];return n[o]=a,t(n[o],a)}return md(n,o,i(s)),!0}});var py=g((f7e,hG)=>{"use strict";var mG=Ae(),gG=mG("%TypeError%"),yxe=mG("%SyntaxError%"),fy=so(),bxe={"Property Descriptor":function(e,t){if(e(t)!=="Object")return!1;var i={"[[Configurable]]":!0,"[[Enumerable]]":!0,"[[Get]]":!0,"[[Set]]":!0,"[[Value]]":!0,"[[Writable]]":!0};for(var n in t)if(fy(t,n)&&!i[n])return!1;var o=fy(t,"[[Value]]"),s=fy(t,"[[Get]]")||fy(t,"[[Set]]");if(o&&s)throw new gG("Property Descriptors may not be both accessor and data descriptors");return!0}};hG.exports=function(e,t,i,n){var o=bxe[t];if(typeof o!="function")throw new yxe("unknown record type: "+t);if(!o(e,n))throw new gG(i+" must be a "+t)}});var yG=g((p7e,vG)=>{"use strict";var wxe=py(),xxe=pr();vG.exports=function(e){if(typeof e=="undefined")return e;wxe(xxe,"Property Descriptor","Desc",e);var t={};return"[[Value]]"in e&&(t.value=e["[[Value]]"]),"[[Writable]]"in e&&(t.writable=e["[[Writable]]"]),"[[Get]]"in e&&(t.get=e["[[Get]]"]),"[[Set]]"in e&&(t.set=e["[[Set]]"]),"[[Enumerable]]"in e&&(t.enumerable=e["[[Enumerable]]"]),"[[Configurable]]"in e&&(t.configurable=e["[[Configurable]]"]),t}});var xG=g((d7e,bG)=>{"use strict";var wG=so(),Dxe=py(),Sxe=pr();bG.exports=function(e){return!(typeof e=="undefined"||(Dxe(Sxe,"Property Descriptor","Desc",e),!wG(e,"[[Get]]")&&!wG(e,"[[Set]]")))}});var EG=g((h7e,DG)=>{"use strict";var SG=so(),Exe=py(),Cxe=pr();DG.exports=function(e){return!(typeof e=="undefined"||(Exe(Cxe,"Property Descriptor","Desc",e),!SG(e,"[[Value]]")&&!SG(e,"[[Writable]]")))}});var PG=g((m7e,CG)=>{"use strict";var Rn=so(),_xe=Ae(),dy=_xe("%TypeError%"),Pxe=pr(),U_=__(),_G=iy();CG.exports=function(e){if(Pxe(e)!=="Object")throw new dy("ToPropertyDescriptor requires an object");var t={};if(Rn(e,"enumerable")&&(t["[[Enumerable]]"]=U_(e.enumerable)),Rn(e,"configurable")&&(t["[[Configurable]]"]=U_(e.configurable)),Rn(e,"value")&&(t["[[Value]]"]=e.value),Rn(e,"writable")&&(t["[[Writable]]"]=U_(e.writable)),Rn(e,"get")){var i=e.get;if(typeof i!="undefined"&&!_G(i))throw new dy("getter must be a function");t["[[Get]]"]=i}if(Rn(e,"set")){var n=e.set;if(typeof n!="undefined"&&!_G(n))throw new dy("setter must be a function");t["[[Set]]"]=n}if((Rn(t,"[[Get]]")||Rn(t,"[[Set]]"))&&(Rn(t,"[[Value]]")||Rn(t,"[[Writable]]")))throw new dy("Invalid property descriptor. Cannot both specify accessors and a value or writable attribute");return t}});var IG=g((g7e,TG)=>{"use strict";var Txe=Ae(),W_=Txe("%TypeError%"),RG=fG(),Rxe=dG(),kxe=yG(),kG=xG(),H_=EG(),Ixe=Hu(),Fxe=B_(),Axe=PG(),z_=pr();TG.exports=function(e,t,i){if(z_(e)!=="Object")throw new W_("Assertion failed: Type(O) is not Object");if(!Ixe(t))throw new W_("Assertion failed: IsPropertyKey(P) is not true");var n=RG({Type:z_,IsDataDescriptor:H_,IsAccessorDescriptor:kG},i)?i:Axe(i);if(!RG({Type:z_,IsDataDescriptor:H_,IsAccessorDescriptor:kG},n))throw new W_("Assertion failed: Desc is not a valid Property Descriptor");return Rxe(H_,Fxe,kxe,e,t,n)}});var AG=g((v7e,G_)=>{"use strict";var Oxe=Ae(),FG=Oxe("%Reflect.construct%",!0),hy=IG();try{hy({},"",{"[[Get]]":function(){}})}catch(r){hy=null}hy&&FG?(V_={},K_={},hy(K_,"length",{"[[Get]]":function(){throw V_},"[[Enumerable]]":!0}),G_.exports=function(e){try{FG(e,K_)}catch(t){return t===V_}}):G_.exports=function(e){return typeof e=="function"&&!!e.prototype};var V_,K_});var qG=g((y7e,OG)=>{"use strict";var LG=Ae(),MG=LG("%Symbol.species%",!0),J_=LG("%TypeError%"),Lxe=AG(),NG=pr();OG.exports=function(e,t){if(NG(e)!=="Object")throw new J_("Assertion failed: Type(O) is not Object");var i=e.constructor;if(typeof i=="undefined")return t;if(NG(i)!=="Object")throw new J_("O.constructor is not an Object");var n=MG?i[MG]:void 0;if(n==null)return t;if(Lxe(n))return n;throw new J_("no constructor found")}});var Y_=g((b7e,$G)=>{"use strict";var BG=Ae(),Mxe=BG("%Math%"),Nxe=BG("%Number%");$G.exports=Nxe.MAX_SAFE_INTEGER||Mxe.pow(2,53)-1});var UG=g((w7e,jG)=>{"use strict";var qxe=Ae(),$xe=qxe("%Math.abs%");jG.exports=function(e){return $xe(e)}});var HG=g((x7e,WG)=>{"use strict";var Bxe=Math.floor;WG.exports=function(e){return Bxe(e)}});var GG=g((D7e,zG)=>{"use strict";zG.exports=function(e){return+e}});var X_=g((S7e,VG)=>{"use strict";var jxe=Number.isNaN||function(r){return r!==r};VG.exports=Number.isFinite||function(r){return typeof r=="number"&&!jxe(r)&&r!==Infinity&&r!==-Infinity}});var JG=g((E7e,KG)=>{"use strict";KG.exports=function(e){return e>=0?1:-1}});var XG=g((C7e,YG)=>{"use strict";var Uxe=UG(),Wxe=HG(),Hxe=GG(),zxe=uy(),Gxe=X_(),Vxe=JG();YG.exports=function(e){var t=Hxe(e);return zxe(t)?0:t===0||!Gxe(t)?t:Vxe(t)*Wxe(Uxe(t))}});var QG=g((_7e,ZG)=>{"use strict";var Kxe=Ae(),Jxe=Kxe("RegExp.prototype.test"),Yxe=c_();ZG.exports=function(e){return Yxe(Jxe,e)}});var tV=g((P7e,eV)=>{"use strict";eV.exports=function(e){return e===null||typeof e!="function"&&typeof e!="object"}});var iV=g((T7e,rV)=>{"use strict";rV.exports=function(e){return e===null||typeof e!="function"&&typeof e!="object"}});var oV=g((R7e,nV)=>{"use strict";var Xxe=Date.prototype.getDay,Zxe=function(e){try{return Xxe.call(e),!0}catch(t){return!1}},Qxe=Object.prototype.toString,eDe="[object Date]",tDe=typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol";nV.exports=function(e){return typeof e!="object"||e===null?!1:tDe?Zxe(e):Qxe.call(e)===eDe}});var uV=g((k7e,Z_)=>{"use strict";var rDe=Object.prototype.toString,iDe=Li()();iDe?(sV=Symbol.prototype.toString,aV=/^Symbol\(.*\)$/,lV=function(e){return typeof e.valueOf()!="symbol"?!1:aV.test(sV.call(e))},Z_.exports=function(e){if(typeof e=="symbol")return!0;if(rDe.call(e)!=="[object Symbol]")return!1;try{return lV(e)}catch(t){return!1}}):Z_.exports=function(e){return!1};var sV,aV,lV});var dV=g((I7e,cV)=>{"use strict";var nDe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol",Q_=iV(),fV=Oy(),oDe=oV(),pV=uV(),sDe=function(e,t){if(typeof e=="undefined"||e===null)throw new TypeError("Cannot call method on "+e);if(typeof t!="string"||t!=="number"&&t!=="string")throw new TypeError('hint must be "string" or "number"');var i=t==="string"?["toString","valueOf"]:["valueOf","toString"],n,o,s;for(s=0;s1&&(arguments[1]===String?t="string":arguments[1]===Number&&(t="number"));var i;if(nDe&&(Symbol.toPrimitive?i=aDe(e,Symbol.toPrimitive):pV(e)&&(i=Symbol.prototype.valueOf)),typeof i!="undefined"){var n=i.call(e,t);if(Q_(n))return n;throw new TypeError("unable to convert exotic object to primitive")}return t==="default"&&(oDe(e)||pV(e))&&(t="string"),sDe(e,t==="default"?"number":t)}});var gV=g((F7e,hV)=>{"use strict";var mV=dV();hV.exports=function(e){return arguments.length>1?mV(e,arguments[1]):mV(e)}});var SV=g((A7e,vV)=>{"use strict";var my=Ae(),lDe=my("%TypeError%"),yV=my("%Number%"),uDe=my("%RegExp%"),bV=my("%parseInt%"),wV=Ra(),gy=QG(),cDe=tV(),xV=wV("String.prototype.slice"),fDe=gy(/^0b[01]+$/i),pDe=gy(/^0o[0-7]+$/i),dDe=gy(/^[-+]0x[0-9a-f]+$/i),hDe=["\x85","\u200B","\uFFFE"].join(""),mDe=new uDe("["+hDe+"]","g"),gDe=gy(mDe),DV=[` +\v\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003`,"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028","\u2029\uFEFF"].join(""),vDe=new RegExp("(^["+DV+"]+)|(["+DV+"]+$)","g"),yDe=wV("String.prototype.replace"),bDe=function(r){return yDe(r,vDe,"")},wDe=gV();vV.exports=function r(e){var t=cDe(e)?e:wDe(e,yV);if(typeof t=="symbol")throw new lDe("Cannot convert a Symbol value to a number");if(typeof t=="string"){if(fDe(t))return r(bV(xV(t,2),2));if(pDe(t))return r(bV(xV(t,2),8));if(gDe(t)||dDe(t))return NaN;var i=bDe(t);if(i!==t)return r(i)}return yV(t)}});var CV=g((O7e,EV)=>{"use strict";var xDe=XG(),DDe=SV();EV.exports=function(e){var t=DDe(e);return t!==0&&(t=xDe(t)),t===0?0:t}});var eP=g((L7e,_V)=>{"use strict";var PV=Y_(),SDe=CV();_V.exports=function(e){var t=SDe(e);return t<=0?0:t>PV?PV:t}});var tP=g((M7e,TV)=>{"use strict";TV.exports=function(e){return typeof e=="number"&&e>=55296&&e<=56319}});var rP=g((N7e,RV)=>{"use strict";RV.exports=function(e){return typeof e=="number"&&e>=56320&&e<=57343}});var AV=g((q7e,kV)=>{"use strict";var IV=Ae(),EDe=IV("%TypeError%"),FV=IV("%String.fromCharCode%"),CDe=tP(),_De=rP();kV.exports=function(e,t){if(!CDe(e)||!_De(t))throw new EDe("Assertion failed: `lead` must be a leading surrogate char code, and `trail` must be a trailing surrogate char code");return FV(e)+FV(t)}});var $V=g(($7e,OV)=>{"use strict";var PDe=Ae(),LV=PDe("%TypeError%"),MV=Ra(),TDe=tP(),NV=rP(),RDe=pr(),kDe=AV(),IDe=MV("String.prototype.charAt"),qV=MV("String.prototype.charCodeAt");OV.exports=function(e,t){if(RDe(e)!=="String")throw new LV("Assertion failed: `string` must be a String");var i=e.length;if(t<0||t>=i)throw new LV("Assertion failed: `position` must be >= 0, and < the length of `string`");var n=qV(e,t),o=IDe(e,t),s=TDe(n),a=NV(n);if(!s&&!a)return{"[[CodePoint]]":o,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!1};if(a||t+1===i)return{"[[CodePoint]]":o,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0};var l=qV(e,t+1);return NV(l)?{"[[CodePoint]]":kDe(n,l),"[[CodeUnitCount]]":2,"[[IsUnpairedSurrogate]]":!1}:{"[[CodePoint]]":o,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0}}});var jV=g((B7e,BV)=>{"use strict";var FDe=Ae(),ADe=FDe("%Math.abs%");BV.exports=function(e){return ADe(e)}});var WV=g((j7e,UV)=>{"use strict";var ODe=Math.floor;UV.exports=function(e){return ODe(e)}});var zV=g((U7e,HV)=>{"use strict";var LDe=jV(),MDe=WV(),NDe=uy(),qDe=X_();HV.exports=function(e){if(typeof e!="number"||NDe(e)||!qDe(e))return!1;var t=LDe(e);return MDe(t)===t}});var KV=g((W7e,GV)=>{"use strict";var $De=Ae(),BDe=$V(),jDe=zV(),VV=pr(),UDe=Y_(),iP=$De("%TypeError%");GV.exports=function(e,t,i){if(VV(e)!=="String")throw new iP("Assertion failed: `S` must be a String");if(!jDe(t)||t<0||t>UDe)throw new iP("Assertion failed: `length` must be an integer >= 0 and <= 2**53");if(VV(i)!=="Boolean")throw new iP("Assertion failed: `unicode` must be a Boolean");if(!i)return t+1;var n=e.length;if(t+1>=n)return t+1;var o=BDe(e,t);return t+o["[[CodeUnitCount]]"]}});var YV=g((H7e,JV)=>{"use strict";var WDe=Ae(),HDe=WDe("%TypeError%"),zDe=pr();JV.exports=function(e,t){if(zDe(t)!=="Boolean")throw new HDe("Assertion failed: Type(done) is not Boolean");return{value:e,done:t}}});var QV=g((z7e,XV)=>{"use strict";var GDe=Ae(),ZV=GDe("%Array%"),VDe=!ZV.isArray&&Ra()("Object.prototype.toString");XV.exports=ZV.isArray||function(e){return VDe(e)==="[object Array]"}});var nK=g((G7e,eK)=>{"use strict";var nP=Ae(),tK=nP("%Object.create%",!0),rK=nP("%TypeError%"),iK=nP("%SyntaxError%"),KDe=QV(),JDe=pr(),YDe=!({__proto__:null}instanceof Object);eK.exports=function(e){if(e!==null&&JDe(e)!=="Object")throw new rK("Assertion failed: `proto` must be null or an object");var t=arguments.length<2?[]:arguments[1];if(!KDe(t))throw new rK("Assertion failed: `additionalInternalSlotsList` must be an Array");if(t.length>0)throw new iK("es-abstract does not yet support internal slots");if(tK)return tK(e);if(YDe)return{__proto__:e};if(e===null)throw new iK("native Object.create support is required to create null objects");var i=function(){};return i.prototype=e,new i}});var sK=g((V7e,oK)=>{"use strict";var XDe=Ae(),oP=XDe("%TypeError%"),ZDe=Ra()("RegExp.prototype.exec"),QDe=f_(),e0e=fd(),t0e=iy(),sP=pr();oK.exports=function(e,t){if(sP(e)!=="Object")throw new oP("Assertion failed: `R` must be an Object");if(sP(t)!=="String")throw new oP("Assertion failed: `S` must be a String");var i=e0e(e,"exec");if(t0e(i)){var n=QDe(i,e,[t]);if(n===null||sP(n)==="Object")return n;throw new oP('"exec" method must return `null` or an Object')}return ZDe(e,t)}});var lK=g((K7e,aK)=>{"use strict";var aP=Vv(),Gu=P_(),r0e=w_(),i0e=aP("%TypeError%"),vy=aP("%WeakMap%",!0),yy=aP("%Map%",!0),n0e=Gu("WeakMap.prototype.get",!0),o0e=Gu("WeakMap.prototype.set",!0),s0e=Gu("WeakMap.prototype.has",!0),a0e=Gu("Map.prototype.get",!0),l0e=Gu("Map.prototype.set",!0),u0e=Gu("Map.prototype.has",!0),lP=function(r,e){for(var t=r,i;(i=t.next)!==null;t=i)if(i.key===e)return t.next=i.next,i.next=r.next,r.next=i,i},c0e=function(r,e){var t=lP(r,e);return t&&t.value},f0e=function(r,e,t){var i=lP(r,e);i?i.value=t:r.next={key:e,next:r.next,value:t}},p0e=function(r,e){return!!lP(r,e)};aK.exports=function(){var e,t,i,n={assert:function(o){if(!n.has(o))throw new i0e("Side channel does not contain "+r0e(o))},get:function(o){if(vy&&o&&(typeof o=="object"||typeof o=="function")){if(e)return n0e(e,o)}else if(yy){if(t)return a0e(t,o)}else if(i)return c0e(i,o)},has:function(o){if(vy&&o&&(typeof o=="object"||typeof o=="function")){if(e)return s0e(e,o)}else if(yy){if(t)return u0e(t,o)}else if(i)return p0e(i,o);return!1},set:function(o,s){vy&&o&&(typeof o=="object"||typeof o=="function")?(e||(e=new vy),o0e(e,o,s)):yy?(t||(t=new yy),l0e(t,o,s)):(i||(i={key:{},next:null}),f0e(i,o,s))}};return n}});var fK=g((J7e,uK)=>{"use strict";var d0e=L_(),h0e=so(),gd=lK()(),hs=d0e("%TypeError%"),cK={assert:function(r,e){if(!r||typeof r!="object"&&typeof r!="function")throw new hs("`O` is not an object");if(typeof e!="string")throw new hs("`slot` must be a string");gd.assert(r)},get:function(r,e){if(!r||typeof r!="object"&&typeof r!="function")throw new hs("`O` is not an object");if(typeof e!="string")throw new hs("`slot` must be a string");var t=gd.get(r);return t&&t["$"+e]},has:function(r,e){if(!r||typeof r!="object"&&typeof r!="function")throw new hs("`O` is not an object");if(typeof e!="string")throw new hs("`slot` must be a string");var t=gd.get(r);return!!t&&h0e(t,"$"+e)},set:function(r,e,t){if(!r||typeof r!="object"&&typeof r!="function")throw new hs("`O` is not an object");if(typeof e!="string")throw new hs("`slot` must be a string");var i=gd.get(r);i||(i={},gd.set(r,i)),i["$"+e]=t}};Object.freeze&&Object.freeze(cK);uK.exports=cK});var gK=g((Y7e,pK)=>{"use strict";var dK=Fn(),m0e=KV(),by=YV(),hK=fd(),g0e=Ae(),v0e=nK(),y0e=sK(),b0e=j_(),w0e=eP(),x0e=oy(),wy=pr(),D0e=Li()(),Jt=fK(),mK,lo=function(e,t,i,n){if(wy(t)!=="String")throw new TypeError("S must be a string");if(wy(i)!=="Boolean")throw new TypeError("global must be a boolean");if(wy(n)!=="Boolean")throw new TypeError("fullUnicode must be a boolean");Jt.set(this,"[[IteratingRegExp]]",e),Jt.set(this,"[[IteratedString]]",t),Jt.set(this,"[[Global]]",i),Jt.set(this,"[[Unicode]]",n),Jt.set(this,"[[Done]]",!1)},uP=g0e("%IteratorPrototype%",!0);uP&&(lo.prototype=v0e(uP));dK(lo.prototype,{next:function(){var e=this;if(wy(e)!=="Object")throw new TypeError("receiver must be an object");if(!(e instanceof lo)||!Jt.has(e,"[[IteratingRegExp]]")||!Jt.has(e,"[[IteratedString]]")||!Jt.has(e,"[[Global]]")||!Jt.has(e,"[[Unicode]]")||!Jt.has(e,"[[Done]]"))throw new TypeError('"this" value must be a RegExpStringIterator instance');if(Jt.get(e,"[[Done]]"))return by(mK,!0);var t=Jt.get(e,"[[IteratingRegExp]]"),i=Jt.get(e,"[[IteratedString]]"),n=Jt.get(e,"[[Global]]"),o=Jt.get(e,"[[Unicode]]"),s=y0e(t,i);if(s===null)return Jt.set(e,"[[Done]]",!0),by(mK,!0);if(n){var a=x0e(hK(s,"0"));if(a===""){var l=w0e(hK(t,"lastIndex")),u=m0e(i,l,o);b0e(t,"lastIndex",u,!0)}return by(s,!1)}return Jt.set(e,"[[Done]]",!0),by(s,!1)}});D0e&&(cP=Object.defineProperty,Symbol.toStringTag&&(cP?cP(lo.prototype,Symbol.toStringTag,{configurable:!0,enumerable:!1,value:"RegExp String Iterator",writable:!1}):lo.prototype[Symbol.toStringTag]="RegExp String Iterator"),!uP&&Symbol.iterator&&(xy={},xy[Symbol.iterator]=lo.prototype[Symbol.iterator]||function(){return this},fP={},fP[Symbol.iterator]=function(){return lo.prototype[Symbol.iterator]!==xy[Symbol.iterator]},dK(lo.prototype,xy,fP)));var cP,xy,fP;pK.exports=lo});var SK=g((X7e,vK)=>{"use strict";var yK=fd(),S0e=j_(),E0e=qG(),C0e=eP(),bK=oy(),Dy=pr(),_0e=$_(),P0e=gK(),wK=RegExp,T0e=function(e,t,i,n){if(Dy(t)!=="String")throw new TypeError('"S" value must be a String');if(Dy(i)!=="Boolean")throw new TypeError('"global" value must be a Boolean');if(Dy(n)!=="Boolean")throw new TypeError('"fullUnicode" value must be a Boolean');var o=new P0e(e,t,i,n);return o},R0e="flags"in RegExp.prototype,k0e=function(e,t){var i,n="flags"in t?yK(t,"flags"):bK(_0e(t));return R0e&&typeof n=="string"?i=new e(t,n):e===wK?i=new e(t.source,n):i=new e(t,n),{flags:n,matcher:i}},pP=function(e){var t=this;if(Dy(t)!=="Object")throw new TypeError('"this" value must be an Object');var i=bK(e),n=E0e(t,wK),o=k0e(n,t),s=o.flags,a=o.matcher,l=C0e(yK(t,"lastIndex"));S0e(a,"lastIndex",l,!0);var u=s.indexOf("g")>-1,c=s.indexOf("u")>-1;return T0e(a,i,u,c)},xK=Object.defineProperty,DK=Object.getOwnPropertyDescriptor;xK&&DK&&(dP=DK(pP,"name"),dP&&dP.configurable&&xK(pP,"name",{value:"[Symbol.matchAll]"}));var dP;vK.exports=pP});var hP=g((Z7e,EK)=>{"use strict";var I0e=Li()(),F0e=SK();EK.exports=function(){return!I0e||typeof Symbol.matchAll!="symbol"||typeof RegExp.prototype[Symbol.matchAll]!="function"?F0e:RegExp.prototype[Symbol.matchAll]}});var mP=g((Q7e,CK)=>{"use strict";var _K=f_(),A0e=fd(),O0e=_7(),PK=L7(),TK=oy(),RK=x_(),L0e=P_(),M0e=Li()(),N0e=$_(),q0e=L0e("String.prototype.indexOf"),$0e=hP(),kK=function(e){var t=$0e();if(M0e&&typeof Symbol.matchAll=="symbol"){var i=O0e(e,Symbol.matchAll);return i===RegExp.prototype[Symbol.matchAll]&&i!==t?t:i}if(PK(e))return t};CK.exports=function(e){var t=RK(this);if(typeof e!="undefined"&&e!==null){var i=PK(e);if(i){var n="flags"in e?A0e(e,"flags"):N0e(e);if(RK(n),q0e(TK(n),"g")<0)throw new TypeError("matchAll requires a global regular expression")}var o=kK(e);if(typeof o!="undefined")return _K(o,e,[t])}var s=TK(t),a=new RegExp(e,"g");return _K(kK(a),a,[s])}});var gP=g((eGe,IK)=>{"use strict";var B0e=mP();IK.exports=function(){if(String.prototype.matchAll)try{"".matchAll(RegExp.prototype)}catch(e){return String.prototype.matchAll}return B0e}});var LK=g((tGe,FK)=>{"use strict";var vP=Fn(),j0e=Li()(),U0e=gP(),W0e=hP(),AK=Object.defineProperty,OK=Object.getOwnPropertyDescriptor;FK.exports=function(){var e=U0e();if(vP(String.prototype,{matchAll:e},{matchAll:function(){return String.prototype.matchAll!==e}}),j0e){var t=Symbol.matchAll||(Symbol.for?Symbol.for("Symbol.matchAll"):Symbol("Symbol.matchAll"));if(vP(Symbol,{matchAll:t},{matchAll:function(){return Symbol.matchAll!==t}}),AK&&OK){var i=OK(Symbol,t);(!i||i.configurable)&&AK(Symbol,t,{configurable:!1,enumerable:!1,value:t,writable:!1})}var n=W0e(),o={};o[t]=n;var s={};s[t]=function(){return RegExp.prototype[t]!==n},vP(RegExp.prototype,o,s)}return e}});var $K=g((rGe,MK)=>{"use strict";var H0e=i_(),z0e=Fn(),NK=mP(),G0e=gP(),V0e=LK(),qK=H0e(NK);z0e(qK,{getPolyfill:G0e,implementation:NK,shim:V0e});MK.exports=qK});var CJ=g(nSe=>{fo(nSe,{default:()=>sSe});var DJ=S(Lw()),SJ=S(Ab()),EJ=S(Pf()),co=j()("attach"),oSe=global.hasOwnProperty("__TEST__"),sSe=(r,e=!0)=>{let t=DJ.attach(r,SJ.default.getLogger("node-client"),e);global.hasOwnProperty("__TEST__")||t.call("coc#util#path_replace_patterns").then(s=>{if(wt(s)){let a=$.file;$.file=l=>(l=l.replace(/\\/g,"/"),Object.keys(s).forEach(u=>l=l.replace(new RegExp("^"+u),s[u])),a(l))}}).logError(),t.setVar("coc_process_pid",process.pid,!0);let i=new xJ(t),n=!1,o=!1;return t.on("notification",async(s,a)=>{switch(s){case"VimEnter":{!o&&n&&(o=!0,await i.init());break}case"TaskExit":case"TaskStderr":case"TaskStdout":case"GlobalChange":case"PromptInsert":case"InputChar":case"MenuInput":case"OptionSet":case"FloatBtnClick":await A.fire(s,a);break;case"CocAutocmd":co.debug("Notification autocmd:",...a),await A.fire(a[0],a.slice(1));break;default:{if(!i.hasAction(s)){if(global.hasOwnProperty("__TEST__"))return;console.error(`action "${s}" not registered`);return}try{i.isReady?co.info("receive notification:",s,a):co.warn(`Plugin not ready when received "${s}"`,a),await i.ready,await i.cocAction(s,...a)}catch(u){console.error(`Error on notification "${s}": ${u.message||u.toString()}`),co.error("Notification error:",s,a,u)}}}}),t.on("request",async(s,a,l)=>{s!="redraw"&&co.info("receive request:",s,a);let u=setTimeout(()=>{co.error("Request cost more than 3s",s,a)},3e3);try{if(s=="CocAutocmd")co.debug("Request autocmd:",...a),await A.fire(a[0],a.slice(1)),l.send();else{i.isReady||co.warn(`Plugin not ready when received "${s}"`,a);let c=await i.cocAction(s,...a);l.send(c)}clearTimeout(u)}catch(c){clearTimeout(u),l.send(c.message||c.toString(),!0),co.error("Request error:",s,a,c)}}),t.channelId.then(async s=>{n=!0,oSe&&t.command(`let g:coc_node_channel_id = ${s}`,!0);let{major:a,minor:l,patch:u}=EJ.default.parse(ug);t.setClientInfo("coc",{major:a,minor:l,patch:u},"remote",{},{}),await t.getVvar("vim_did_enter")&&!o&&(o=!0,await i.init())}).catch(s=>{console.error(`Channel create error: ${s.message}`)}),i}});var aSe=qT();gh();Object.defineProperty(console,"log",{value(){LP.info(...arguments)}});aSe.shim();var LP=j()("server");var Ox=S(W());var nq=S(require("child_process")),oq=S(Gr()),sq=S(require("fs")),aq=S(Ex()),kx=S(require("path")),Ix=S(W());"use strict";var Ile=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var o in n)n.hasOwnProperty(o)&&(i[o]=n[o])},r(e,t)};return function(e,t){r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),ct,mf;typeof process=="object"?mf=process.platform==="win32":typeof navigator=="object"&&(AN=navigator.userAgent,mf=AN.indexOf("Windows")>=0);var AN;var Fle=/^\w[\w\d+.-]*$/,Ale=/^\//,Ole=/^\/\//;function Lle(r,e){if(!r.scheme&&e)throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "'+r.authority+'", path: "'+r.path+'", query: "'+r.query+'", fragment: "'+r.fragment+'"}');if(r.scheme&&!Fle.test(r.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(r.path){if(r.authority){if(!Ale.test(r.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(Ole.test(r.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function Mle(r,e){return!r&&!e?"file":r}function Nle(r,e){switch(r){case"https":case"http":case"file":e?e[0]!==zi&&(e=zi+e):e=zi;break}return e}var Ke="",zi="/",qle=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,$=function(){function r(e,t,i,n,o,s){s===void 0&&(s=!1),typeof e=="object"?(this.scheme=e.scheme||Ke,this.authority=e.authority||Ke,this.path=e.path||Ke,this.query=e.query||Ke,this.fragment=e.fragment||Ke):(this.scheme=Mle(e,s),this.authority=t||Ke,this.path=Nle(this.scheme,i||Ke),this.query=n||Ke,this.fragment=o||Ke,Lle(this,s))}return r.isUri=function(e){return e instanceof r?!0:e?typeof e.authority=="string"&&typeof e.fragment=="string"&&typeof e.path=="string"&&typeof e.query=="string"&&typeof e.scheme=="string"&&typeof e.fsPath=="function"&&typeof e.with=="function"&&typeof e.toString=="function":!1},Object.defineProperty(r.prototype,"fsPath",{get:function(){return LN(this,!1)},enumerable:!0,configurable:!0}),r.prototype.with=function(e){if(!e)return this;var t=e.scheme,i=e.authority,n=e.path,o=e.query,s=e.fragment;return t===void 0?t=this.scheme:t===null&&(t=Ke),i===void 0?i=this.authority:i===null&&(i=Ke),n===void 0?n=this.path:n===null&&(n=Ke),o===void 0?o=this.query:o===null&&(o=Ke),s===void 0?s=this.fragment:s===null&&(s=Ke),t===this.scheme&&i===this.authority&&n===this.path&&o===this.query&&s===this.fragment?this:new Dl(t,i,n,o,s)},r.parse=function(e,t){t===void 0&&(t=!1);var i=qle.exec(e);return i?new Dl(i[2]||Ke,om(i[4]||Ke),om(i[5]||Ke),om(i[7]||Ke),om(i[9]||Ke),t):new Dl(Ke,Ke,Ke,Ke,Ke)},r.file=function(e){var t=Ke;if(mf&&(e=e.replace(/\\/g,zi)),e[0]===zi&&e[1]===zi){var i=e.indexOf(zi,2);i===-1?(t=e.substring(2),e=zi):(t=e.substring(2,i),e=e.substring(i)||zi)}return new Dl("file",t,e,Ke,Ke)},r.from=function(e){return new Dl(e.scheme,e.authority,e.path,e.query,e.fragment)},r.prototype.toString=function(e){return e===void 0&&(e=!1),Cx(this,e)},r.prototype.toJSON=function(){return this},r.revive=function(e){if(e){if(e instanceof r)return e;var t=new Dl(e);return t._formatted=e.external,t._fsPath=e._sep===ON?e.fsPath:null,t}else return e},r}();var ON=mf?1:void 0,Dl=function(r){Ile(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t._formatted=null,t._fsPath=null,t}return Object.defineProperty(e.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=LN(this,!1)),this._fsPath},enumerable:!0,configurable:!0}),e.prototype.toString=function(t){return t===void 0&&(t=!1),t?Cx(this,!0):(this._formatted||(this._formatted=Cx(this,!1)),this._formatted)},e.prototype.toJSON=function(){var t={$mid:1};return this._fsPath&&(t.fsPath=this._fsPath,t._sep=ON),this._formatted&&(t.external=this._formatted),this.path&&(t.path=this.path),this.scheme&&(t.scheme=this.scheme),this.authority&&(t.authority=this.authority),this.query&&(t.query=this.query),this.fragment&&(t.fragment=this.fragment),t},e}($),MN=(ct={},ct[58]="%3A",ct[47]="%2F",ct[63]="%3F",ct[35]="%23",ct[91]="%5B",ct[93]="%5D",ct[64]="%40",ct[33]="%21",ct[36]="%24",ct[38]="%26",ct[39]="%27",ct[40]="%28",ct[41]="%29",ct[42]="%2A",ct[43]="%2B",ct[44]="%2C",ct[59]="%3B",ct[61]="%3D",ct[32]="%20",ct);function NN(r,e){for(var t=void 0,i=-1,n=0;n=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||o===45||o===46||o===95||o===126||e&&o===47)i!==-1&&(t+=encodeURIComponent(r.substring(i,n)),i=-1),t!==void 0&&(t+=r.charAt(n));else{t===void 0&&(t=r.substr(0,n));var s=MN[o];s!==void 0?(i!==-1&&(t+=encodeURIComponent(r.substring(i,n)),i=-1),t+=s):i===-1&&(i=n)}}return i!==-1&&(t+=encodeURIComponent(r.substring(i))),t!==void 0?t:r}function $le(r){for(var e=void 0,t=0;t1&&r.scheme==="file"?t="//"+r.authority+r.path:r.path.charCodeAt(0)===47&&(r.path.charCodeAt(1)>=65&&r.path.charCodeAt(1)<=90||r.path.charCodeAt(1)>=97&&r.path.charCodeAt(1)<=122)&&r.path.charCodeAt(2)===58?e?t=r.path.substr(1):t=r.path[1].toLowerCase()+r.path.substr(2):t=r.path,mf&&(t=t.replace(/\//g,"\\")),t}function Cx(r,e){var t=e?$le:NN,i="",n=r.scheme,o=r.authority,s=r.path,a=r.query,l=r.fragment;if(n&&(i+=n,i+=":"),(o||n==="file")&&(i+=zi,i+=zi),o){var u=o.indexOf("@");if(u!==-1){var c=o.substr(0,u);o=o.substr(u+1),u=c.indexOf(":"),u===-1?i+=t(c,!1):(i+=t(c.substr(0,u),!1),i+=":",i+=t(c.substr(u+1),!1)),i+="@"}o=o.toLowerCase(),u=o.indexOf(":"),u===-1?i+=t(o,!1):(i+=t(o.substr(0,u),!1),i+=o.substr(u))}if(s){if(s.length>=3&&s.charCodeAt(0)===47&&s.charCodeAt(2)===58){var f=s.charCodeAt(1);f>=65&&f<=90&&(s="/"+String.fromCharCode(f+32)+":"+s.substr(3))}else if(s.length>=2&&s.charCodeAt(1)===58){var f=s.charCodeAt(0);f>=65&&f<=90&&(s=String.fromCharCode(f+32)+":"+s.substr(2))}i+=t(s,!0)}return a&&(i+="?",i+=t(a,!1)),l&&(i+="#",i+=e?l:NN(l,!1)),i}function qN(r){try{return decodeURIComponent(r)}catch(e){return r.length>3?r.substr(0,3)+qN(r.substr(3)):r}}var $N=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function om(r){return r.match($N)?r.replace($N,function(e){return qN(e)}):r}var lq=S(El());var Cl={};fo(Cl,{OS:()=>tue,OperatingSystem:()=>_l,Platform:()=>Hs,globals:()=>eue,isLinux:()=>Jle,isMacintosh:()=>Rx,isNative:()=>Yle,isWeb:()=>Xle,isWindows:()=>Hn,language:()=>Kle,platform:()=>Zle});var am=!1,lm=!1,Px=!1,Tx=!1,Vle=!1,Kle="en";typeof process=="object"&&typeof process.nextTick=="function"&&typeof process.platform=="string"&&(am=process.platform==="win32",lm=process.platform==="darwin",Px=process.platform==="linux",Tx=!0);var Hs;(function(r){r[r.Web=0]="Web",r[r.Mac=1]="Mac",r[r.Linux=2]="Linux",r[r.Windows=3]="Windows"})(Hs||(Hs={}));var um=0;Tx&&(lm?um=1:am?um=3:Px&&(um=2));var Hn=am,Rx=lm,Jle=Px,Yle=Tx,Xle=Vle,Zle=um,Qle=typeof self=="object"?self:typeof global=="object"?global:{},eue=Qle,_l;(function(r){r[r.Windows=1]="Windows",r[r.Macintosh=2]="Macintosh",r[r.Linux=3]="Linux"})(_l||(_l={}));var tue=lm?2:am?1:3;var pPe=j()("util-index"),Gi="coc-settings.json";function He(r){return new Promise(e=>{setTimeout(()=>{e(void 0)},r)})}function uq(r,e,t,i){return r?(Hn&&!i&&!r.startsWith("jdt://")&&(r=kx.default.win32.normalize(r)),kx.default.isAbsolute(r)?$.file(r).toString():aq.default.isValid(r)?$.parse(r).toString():t!=""?`${t}:${e}`:`unknown:${e}`):`untitled:${e}`}function z(r){for(;r.length;){let e=r.pop();e&&e.dispose()}}function gf(r){try{lq.default.sync(r)}catch(e){return!1}return!0}function hn(r,e={},t){return Hn||(e.shell=e.shell||process.env.SHELL),e.maxBuffer=500*1024,new Promise((i,n)=>{let o;t&&(o=setTimeout(()=>{n(new Error(`timeout after ${t}s`))},t*1e3)),nq.exec(r,e,(s,a,l)=>{if(o&&clearTimeout(o),s){n(new Error(`exited with ${s.code} +${s} +${l}`));return}i(a)})})}function Pl(r,e){let t=oq.default(e,100);try{let i=sq.default.watch(r,{persistent:!0,recursive:!1,encoding:"utf8"},()=>{t()});return Ix.Disposable.create(()=>{t.clear(),i.close()})}catch(i){return Ix.Disposable.create(()=>{t.clear()})}}function cq(r){try{return process.kill(r,0)==!0}catch(e){return e.code==="EPERM"}}function Fx(r){return r=="n"||r=="o"||r=="x"||r=="v"?"":r=="i"?"":r=="s"?"":""}function vf(r,e,t=3){if(r.length==0)return Promise.resolve();let i=0,n=r.length,o=r.slice();return new Promise(s=>{let a=l=>{let u=()=>{if(i=i+1,i==n)s();else if(o.length){let c=o.shift();a(c)}};e(l).then(u,u)};for(let l=0;l{r[t]&&typeof r[t]=="object"?e[t]=zn(r[t]):e[t]=r[t]}),e}var iue=Object.prototype.hasOwnProperty;function fq(r){if(!r||typeof r!="object")return r;let e=[r];for(;e.length>0;){let t=e.shift();Object.freeze(t);for(let i in t)if(iue.call(t,i)){let n=t[i];typeof n=="object"&&!Object.isFrozen(n)&&e.push(n)}}return r}function Ax(r,e,t=!0){return wt(r)?(wt(e)&&Object.keys(e).forEach(i=>{i in r?t&&(wt(r[i])&&wt(e[i])?Ax(r[i],e[i],t):r[i]=e[i]):r[i]=e[i]}),r):e}function Ne(r,e){if(r===e)return!0;if(r==null||e===null||e===void 0||typeof r!=typeof e||typeof r!="object"||Array.isArray(r)!==Array.isArray(e))return!1;let t,i;if(Array.isArray(r)){if(r.length!==e.length)return!1;for(t=0;tn(t)))}catch(n){n.message&&n.message.indexOf("transport disconnected")==-1&&console.error(`Error on ${e}: ${n.message}${n.stack?` +`+n.stack:""} `),pq.error(`Handler Error on ${e}`,n.stack)}}on(e,t,i,n){if(Array.isArray(e)){let o=n||[];for(let s of e)this.on(s,t,i,o);return Ox.Disposable.create(()=>{z(o)})}else{let o=this.handlers.get(e)||[],s=Error().stack,a=u=>new Promise((c,f)=>{let p;try{Promise.resolve(t.apply(i||null,u)).then(()=>{p&&clearTimeout(p),c(void 0)},d=>{p&&clearTimeout(p),f(d)}),p=setTimeout(()=>{pq.warn(`Handler of ${e} blocked more than 2s:`,s)},2e3)}catch(d){f(d)}});o.push(a),this.handlers.set(e,o);let l=Ox.Disposable.create(()=>{let u=o.indexOf(a);u!==-1&&o.splice(u,1)});return n&&n.push(l),l}}},A=new dq;var bJ=S(require("events")),wJ=S(require("path")),AP=S(require("fs")),xd=S(W());var Wv=S(W());var Xj=S(Gr()),Zj=S(Pf()),dt=S(W());var LB=S(Gr()),Lm=S(W());var hD=S(x$());var bB=S(uB());var wr=S(hB());function mB(r){return`${wr.default.gray.open}${r}${wr.default.gray.close}`}function lD(r){return`${wr.default.magenta.open}${r}${wr.default.magenta.close}`}function gB(r){return`${wr.default.bold.open}${r}${wr.default.bold.close}`}function Am(r){return`${wr.default.underline.open}${r}${wr.default.underline.close}`}function vB(r){return`${wr.default.italic.open}${r}${wr.default.italic.close}`}function yB(r){return`${wr.default.yellow.open}${r}${wr.default.yellow.close}`}function uD(r){return`${wr.default.blue.open}${r}${wr.default.blue.close}`}var HTe=j()("markdown-renderer"),wB="^*||*^",cD="*|*|*|*",wpe=new RegExp(xB(cD),"g"),DB="*#COLON|*",xpe=new RegExp(xB(DB),"g"),Dpe=[" "],Spe="\r",SB={code:Ki,blockquote:Ki,html:mB,heading:lD,firstHeading:lD,hr:Ki,listitem:Ki,list:Epe,table:Ki,paragraph:Ki,strong:gB,em:vB,codespan:yB,del:Am,link:Am,href:Am,text:Ki,unescape:!0,emoji:!1,width:80,showSectionPrefix:!0,tab:2,tableOptions:{}};function EB(r,e){return e?r.replace(Spe,/\n/g):r}function _pe(r,e){return typeof r=="number"?new Array(r+1).join(" "):typeof r=="string"&&Cpe(r)?r:new Array(e+1).join(" ")}function Cpe(r){return Dpe.some(function(e){return r.match("^("+e+")+$")})}function Ppe(r,e){return e.replace(/(^|\n)(.+)/g,"$1"+r+"$2")}function Tpe(r,e){return e&&r+e.split(` +`).join(` +`+r)}var Rpe="\\*",kpe="\\d+\\.",CB="(?:"+[Rpe,kpe].join("|")+")";function Ipe(r,e){let t=new RegExp("(\\S(?: | )?)((?:"+e+")+)("+CB+"(?:.*)+)$","gm");return r.replace(t,`$1 +`+e+"$2$3")}var _B=function(r,e){return r.match("^(?:"+e+")*"+CB)};function PB(r){return" ".repeat(r.length)}var fD="* ";function Fpe(r,e){return _B(e,r)?e:PB(fD)+e}function Ape(r,e){let t=Fpe.bind(null,e);return r.split(` +`).filter(Ki).map(t).join(` +`)}var TB=function(r){return r+". "};function Ope(r,e,t){return _B(e,r)?{num:t+1,line:e.replace(fD,TB(t+1))}:{num:t,line:PB(TB(t))+e}}function Lpe(r,e){let t=Ope.bind(null,e),i=0;return r.split(` +`).filter(Ki).map(n=>{let o=t(n,i);return i=o.num,o.line}).join(` +`)}function Epe(r,e,t){return r=r.trim(),r=e?Lpe(r,t):Ape(r,t),r}function Lf(r){return r+` + +`}function Mpe(r){return r.replace(xpe,":")}function RB(r,e=null){if(!r)return[];e=e||Ki;let t=e(r).split(` +`),i=[];return t.forEach(function(n){if(!n)return;let o=n.replace(wpe,"").split(wB);i.push(o.splice(0,o.length-1))}),i}function xB(r){return r.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function Npe(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function Ki(r){return r}var pD=new Map,kB=class{constructor(e={},t={}){this.options=e;this.highlightOptions=t;this.o=Object.assign({},SB,e),this.tab=_pe(this.o.tab,SB.tab),this.tableSettings=this.o.tableOptions,this.unescape=this.o.unescape?Npe:Ki,this.highlightOptions=t||{},this.transform=this.compose(Mpe,this.unescape)}textLength(e){return e.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g,"").length}text(e){return this.o.text(e)}code(e,t,i){return"``` "+t+` +`+e+"\n```\n"}blockquote(e){return Lf(this.o.blockquote(Tpe(this.tab,e.trim())))}html(e){return this.o.html(e)}heading(e,t,i){return e=this.transform(e),e=(this.o.showSectionPrefix?new Array(t+1).join("#")+" ":"")+e,Lf(t===1?this.o.firstHeading(e):this.o.heading(e))}hr(){return`--- + +`}list(e,t){return e=this.o.list(e,t,this.tab),Lf(Ipe(Ppe(this.tab,e),this.tab))}listitem(e){let t=this.compose(this.o.listitem,this.transform);return e.indexOf(` +`)!==-1&&(e=e.trim()),` +`+fD+t(e)}checkbox(e){return"["+(e?"X":" ")+"] "}paragraph(e){return e=this.compose(this.o.paragraph,this.transform)(e),Lf(e)}table(e,t){let i=new bB.default(Object.assign({},{head:RB(e)[0]},this.tableSettings));return RB(t,this.transform).forEach(function(n){i.push(n)}),Lf(this.o.table(i.toString()))}tablerow(e){return cD+e+cD+` +`}tablecell(e,t){return e+wB}strong(e){return this.o.strong(e)}em(e){return e=EB(e,this.o.reflowText),this.o.em(e)}codespan(e){return e=EB(e,this.o.reflowText),this.o.codespan(e.replace(/:/g,DB))}br(){return` +`}del(e){return this.o.del(e)}link(e,t,i){let n;if(this.options.sanitize){try{n=decodeURIComponent(unescape(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(s){return""}if(n.startsWith("javascript:"))return""}if(i&&e&&i!=e&&pD.set(i,e),i&&i!=e)return uD(i);let o=this.o.href(e);return this.o.link(o)}image(e,t,i){if(typeof this.o.image=="function")return this.o.image(e,t,i);let n="!["+i;return t&&(n+=" \u2013 "+t),n+"]("+e+`) +`}compose(...e){return(...t)=>{for(let i=e.length;i-- >0;)t=[e[i].apply(this,t)];return t[0]}}static getLinks(){let e=[];for(let[t,i]of pD.entries())e.push(`${uD(t)}: ${i}`);return pD.clear(),e}},dD=kB;function ue(r){return Buffer.byteLength(r)}function Ml(r){return r?r[0].toUpperCase()+r.slice(1):""}function Vr(r,e){let t=r.slice(0,e);return Buffer.byteLength(t)}function Mf(r,e){return Buffer.from(r,"utf8").slice(0,e).toString("utf8").length}function Rt(r,e,t){return Buffer.from(r,"utf8").slice(e,t).toString("utf8")}function IB(r){let e=r.charCodeAt(0);return e>128?!1:e==95||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}var FB={30:"black",31:"red",32:"green",33:"yellow",34:"blue",35:"magenta",36:"cyan",37:"white",90:"grey"},AB={40:"black",41:"red",42:"green",43:"yellow",44:"blue",45:"magenta",46:"cyan",47:"white"},OB={1:"bold",3:"italic",4:"underline"};function Nl(r,e=!1){let t=Nf(r),i=[],n="";for(let o of t){if(!o.text)continue;let{foreground:s,background:a,bold:l,italic:u,underline:c}=o,f=ue(n);if(s||a||l||u||c){let p=[f,f+ue(o.text)],d="";s&&a?d=`CocList${Ml(s)}${Ml(a)}`:s?e?s=="yellow"?d="CocMarkdownCode":s=="blue"?d="CocMarkdownLink":s=="magenta"?d="CocMarkdownHeader":d=`CocListFg${Ml(s)}`:d=`CocListFg${Ml(s)}`:a?d=`CocListBg${Ml(a)}`:l?d="CocBold":u?d="CocItalic":c&&(d="CocUnderline"),i.push({span:p,hlGroup:d})}n=n+o.text}return{line:n,highlights:i}}function Nf(r){let e=null,t=null,i="",n=[],o=[],s={},a;a=()=>{let l,u;i.length?i=i.substr(0,i.length-1):o.length&&(l=o.length-1,u=o[l].text,u.length===1?o.pop():o[l].text=u.substr(0,u.length-1))};for(let l=0;l{FB[u]?s.foreground=FB[u]:AB[u]?s.background=AB[u]:u==39?delete s.foreground:u==49?delete s.background:OB[u]?s[OB[u]]=!0:u==22?s.bold=!1:u==23?s.italic=!1:u==24&&(s.underline=!1)}),n=[]):t+=r[l];continue}r[l]==""?e=r[l]:r[l]=="\b"?a():i+=r[l]}return i&&(s.text=i+(e||""),o.push(s)),o}var qpe=["Error","Warning","Info","Hint"],ZTe=j()("markdown-index");hD.default.setOptions({renderer:new dD});function Om(r){let e=[],t=[],i=[],n=0;for(let o of r){let s=e.length,{content:a,filetype:l}=o;if(l=="markdown"){let u=Bpe(a);i.push(...u.codes.map(c=>(c.startLine=c.startLine+s,c.endLine=c.endLine+s,c))),t.push(...u.highlights.map(c=>(c.lnum=c.lnum+s,c))),e.push(...u.lines)}else{let u=a.trim().split(/\r?\n/);qpe.includes(o.filetype)?i.push({hlGroup:`Coc${l}Float`,startLine:s,endLine:s+u.length}):i.push({filetype:o.filetype,startLine:s,endLine:s+u.length}),e.push(...u)}if(o.active){let u=$pe(a,s,o.active);u.length&&t.push(...u)}n!=r.length-1&&e.push("\u2014"),n=n+1}return{lines:e,highlights:t,codes:i}}function $pe(r,e,t){let i=[],[n,o]=t,s=r.split(/\r?\n/),a=0,l=!1;for(let u=0;uo){let f=ue(c.slice(0,o-a));i.push({colStart:0,colEnd:f,lnum:u+e,hlGroup:"CocUnderline"}),l=!1;break}else{let f=ue(c);i.push({colStart:0,colEnd:f,lnum:u+e,hlGroup:"CocUnderline"})}else if(a+c.length>n){l=!0;let f=ue(c.slice(0,n-a));if(a+c.length>o){let p=ue(c.slice(0,o-a));l=!1,i.push({colStart:f,colEnd:p,lnum:u+e,hlGroup:"CocUnderline"});break}else{let p=ue(c);i.push({colStart:f,colEnd:p,lnum:u+e,hlGroup:"CocUnderline"})}}a=a+c.length+1}return i}function Bpe(r){let e=[],t=[],i=[],n=0,o=!1,s,a=0,l=hD.default(r),u=dD.getLinks();u.length&&(l=l+` + +`+u.join(` +`));for(let c of l.replace(/\s*$/,"").split(/\n/)){if(!c.length){let p=e[e.length-1];p&&p.length&&(e.push(c),n++);continue}if(/\s*```\s*([A-Za-z0-9_,]+)?$/.test(c)){let p=e[e.length-1];o?(o=!1,i.push({filetype:s,startLine:a,endLine:n})):(o=!0,s=c.replace(/^\s*```\s*/,""),s=="js"&&(s="javascript"),s=="ts"&&(s="typescript"),s=="bash"&&(s="sh"),a=n),p&&p.length&&(e.push(""),n++);continue}if(o){e.push(c),n++;continue}let f=Nl(c,!0);if(f.highlights)for(let p of f.highlights){let{hlGroup:d,span:h}=p;t.push({hlGroup:d,lnum:n,colStart:h[0],colEnd:h[1]})}e.push(f.line),n++}return{lines:e,highlights:t,codes:i}}var ar=class{constructor(){this.tasks=[];this.count=1}sched(){this.count>0&&this.tasks.length>0&&(this.count--,this.tasks.shift()())}get busy(){return this.count==0}acquire(){return new Promise(e=>{let t=()=>{let i=!1;e(()=>{i||(i=!0,this.count++,this.sched())})};this.tasks.push(t),process.nextTick(this.sched.bind(this))})}use(e){return this.acquire().then(t=>e().then(i=>(t(),i)).catch(i=>{throw t(),i}))}};var MB=process.env.VIM_NODE_RPC=="1",NB=j()("model-float"),mD=class{constructor(e){this.nvim=e;this.winid=0;this._bufnr=0;this.mutex=new ar;this.disposables=[];this.alignTop=!1;this.pumAlignTop=!1;this.autoHide=!0;this.mutex=new ar,A.on("BufEnter",t=>{t==this._bufnr||t==this.targetBufnr||this.close()},null,this.disposables),A.on("InsertEnter",t=>{t==this._bufnr||!this.autoHide||this.close()},null,this.disposables),A.on("InsertLeave",()=>{this.close()},null,this.disposables),A.on("MenuPopupChanged",(t,i)=>{(this.pumAlignTop=i>t.row)==this.alignTop&&this.close()},null,this.disposables),this.onCursorMoved=LB.default(this._onCursorMoved.bind(this),300),A.on("CursorMoved",this.onCursorMoved.bind(this,!1),null,this.disposables),A.on("CursorMovedI",this.onCursorMoved.bind(this,!0),null,this.disposables),this.disposables.push(Lm.Disposable.create(()=>{this.onCursorMoved.clear(),this.cancel()}))}_onCursorMoved(e,t,i){if(t!=this._bufnr&&!(t==this.targetBufnr&&Ne(i,this.cursor))){if(this.autoHide){this.close();return}if(!e||t!=this.targetBufnr){this.close();return}}}async create(e,t=!1,i=0){if(this.onCursorMoved.clear(),e.length==0||e.every(o=>o.content.length==0)){this.close();return}let n=await this.mutex.acquire();try{await this.createPopup(e,{offsetX:i}),n()}catch(o){n(),NB.error("Error on create popup:",o.message),this.close()}}async show(e,t={}){if(this.onCursorMoved.clear(),e.length==0||e.every(n=>n.content.length==0)){this.close();return}let i=await this.mutex.acquire();try{await this.createPopup(e,t),i()}catch(n){i(),NB.error("Error on create popup:",n.message),this.close()}}async createPopup(e,t){let n=(this.tokenSource=new Lm.CancellationTokenSource).token;e=e.filter(m=>m.content.trim().length>0);let{lines:o,codes:s,highlights:a}=Om(e),l={pumAlignTop:this.pumAlignTop,preferTop:typeof t.preferTop=="boolean"?t.preferTop:!1,offsetX:t.offsetX||0,title:t.title||"",close:t.close?1:0,codes:s,highlights:a,modes:t.modes||["n","i","ic","s"]};t.maxHeight&&(l.maxHeight=t.maxHeight),t.maxWidth&&(l.maxWidth=t.maxWidth),t.border&&!t.border.every(m=>m==0)&&(l.border=t.border),t.title&&!l.border&&(l.border=[1,1,1,1]),t.highlight&&(l.highlight=t.highlight),t.borderhighlight&&(l.borderhighlight=[t.borderhighlight]),t.cursorline&&(l.cursorline=1),this.autoHide=t.autoHide!=!1,this.autoHide&&(l.autohide=1);let u=await this.nvim.call("coc#float#create_cursor_float",[this.winid,this._bufnr,o,l]);if(MB&&this.nvim.command("redraw",!0),!u||u.length==0){this.winid=null;return}let[c,f,p,d]=u;if(this.winid=p,n.isCancellationRequested){this.close();return}let h=await this.nvim.call("coc#float#cursor_relative",[p]);h&&(this.alignTop=h.row<0),this._bufnr=d,this.tokenSource.dispose(),this.tokenSource=null,this.targetBufnr=c,this.cursor=f,this.onCursorMoved.clear()}close(){let{winid:e,nvim:t}=this;this.cancel(),e&&(this.winid=0,t.pauseNotification(),t.call("coc#float#close",[e],!0),MB&&this.nvim.command("redraw",!0),t.resumeNotification(!1,!0))}cancel(){let{tokenSource:e}=this;e&&(e.cancel(),this.tokenSource=null)}dispose(){z(this.disposables)}get bufnr(){return this._bufnr}get buffer(){return this.bufnr?this.nvim.createBuffer(this.bufnr):null}get window(){return this.winid?this.nvim.createWindow(this.winid):null}async activated(){return this.winid?await this.nvim.call("coc#float#valid",[this.winid])!=0:!1}},mn=mD;function Ji(r,e){return Wt(r.start,e)===0&&Wt(r.end,e)===0}function Mm(r,e){let{start:t,end:i}=r;return!(Me(i,e.start)<=0||Me(t,e.end)>=0)}function ql(r,e){return!!(Wt(r.start,e)==0||Wt(r.end,e)==0||Ji(e,r))}function qB(r,e){let{start:t,end:i}=e;return r>=t.line&&r<=i.line}function Gn(r){let{start:e,end:t}=r;return e.line==t.line&&e.character==t.character}function Wt(r,e){let{start:t,end:i}=e;return Me(r,t)<0?-1:Me(r,i)>0?1:0}function Me(r,e){return r.line>e.line||e.line==r.line&&r.character>e.character?1:e.line==r.line&&r.character==e.character?0:-1}function jpe(r){return r.start.line==r.end.line}function gD(r,e){let{range:t,newText:i}=e;if(Me(t.end,r)<=0){let n=i.split(` +`),o=n.length-(t.end.line-t.start.line)-1,s=0;if(t.end.line==r.line){let a=jpe(t)&&o==0,l=a?t.end.character-t.start.character:t.end.character;s=(a?i.length:n[n.length-1].length)-l}return{line:o,character:s}}return{line:0,character:0}}function $B(r,e){let{range:t,newText:i}=e;if(Me(t.start,r)>1)return r;let{start:n,end:o}=t,s=i.split(` +`),a=o.line-n.line-s.length+1,l=s[s.length-1],u=r.line-a;if(r.line!=o.line)return{line:u,character:r.character};let c=s.length==1&&n.line!=o.line?n.character:0,f=n.line==o.line&&s.length==1?o.character-n.character:o.character,p=c+r.character+l.length-f;return{line:u,character:p}}function BB(r,e,t){let i=0;for(let n=0;n<=e;n++)n==e?i+=t:i+=r[n].length+1;return i}function jB(r,e,t){if(!Ji(t.range,r))return e;let{start:i,end:n}=t.range,o=e.split(` +`),s=i.line==r.start.line?i.character-r.start.character:i.character,a=BB(o,i.line-r.start.line,s);s=n.line==r.start.line?n.character-r.start.character:n.character;let l=BB(o,n.line-r.start.line,s);return`${e.slice(0,a)}${t.newText}${e.slice(l,e.length)}`}function $l(r,e){let t={line:0,character:0};for(let i of e){let n=gD(r,i);t={line:t.line+n.line,character:t.character+n.character}}return t.line==0&&t.character==0?null:t}var x0=S(require("fs")),Wj=S(require("os")),D0=S(require("path")),Hj=S(W());var uRe=j()("outpubChannel"),vD=class{constructor(e,t){this.name=e;this.nvim=t;this._disposed=!1;this.lines=[""];this.disposables=[]}get content(){return this.lines.join(` +`)}_append(e){let{nvim:t}=this,i=this.lines.length-1,n=e.split(/\r?\n/),o=this.lines[i]+n[0];this.lines[i]=o;let s=n.slice(1);this.lines=this.lines.concat(s),t.pauseNotification(),t.call("setbufline",[this.bufname,"$",o],!0),s.length&&t.call("appendbufline",[this.bufname,"$",s],!0),t.resumeNotification(!1,!0)}append(e){!this.validate()||this._append(e)}appendLine(e){!this.validate()||this._append(e+` +`)}clear(e){if(!this.validate())return;let{nvim:t}=this;this.lines=e?this.lines.slice(-e):[],t.pauseNotification(),t.call("deletebufline",[this.bufname,1,"$"],!0),this.lines.length&&t.call("appendbufline",[this.bufname,"$",this.lines],!0),t.resumeNotification(!1,!0)}hide(){this.nvim.command(`exe 'silent! bd! '.fnameescape('${this.bufname}')`,!0)}get bufname(){return`output:///${this.name}`}show(e){let{nvim:t}=this;t.pauseNotification(),t.command(`exe 'vsplit '.fnameescape('${this.bufname}')`,!0),e&&t.command("wincmd p",!0),t.command("redraw",!0),t.resumeNotification(!1,!0)}validate(){return!this._disposed}dispose(){this._disposed||(this._disposed=!0,this.hide(),this.lines=[],z(this.disposables))}},UB=vD;var No=new Map,WB=class{getProvider(e){return{onDidChange:null,provideTextDocumentContent:async i=>{let n=this.get(i.path.slice(1));return n?(e.pauseNotification(),e.command("setlocal nospell nofoldenable nowrap noswapfile",!0),e.command("setlocal buftype=nofile bufhidden=hide",!0),e.command("setfiletype log",!0),await e.resumeNotification(),n.content):""}}}get names(){return Array.from(No.keys())}get(e){return No.get(e)}create(e,t){if(No.has(e))return No.get(e);if(!/^[\w\s-.]+$/.test(e))throw new Error(`Invalid channel name "${e}", only word characters and white space allowed.`);let i=new UB(e,t);return No.set(e,i),i}show(e,t){let i=No.get(e);!i||i.show(t)}dispose(){for(let e of No.values())e.dispose();No.clear()}},Xs=new WB;var mRe=j()("model-dialog"),yD=class{constructor(e,t){this.nvim=e;this.config=t;this.disposables=[];A.on("BufWinLeave",i=>{i==this.bufnr&&(this.dispose(),t.callback&&t.callback(-1))},null,this.disposables),A.on("FloatBtnClick",(i,n)=>{if(i==this.bufnr){this.dispose();let o=t==null?void 0:t.buttons.filter(s=>s.disabled!=!0);t.callback&&t.callback(o[n].index)}},null,this.disposables)}get lines(){return[...this.config.content.split(/\r?\n/)]}async show(e){let{nvim:t}=this,{title:i,close:n,buttons:o}=this.config,s=this.config.borderhighlight||e.floatBorderHighlight,a=this.config.highlight||e.floatHighlight,l={maxwidth:e.maxWidth||80};i&&(l.title=i),(n||typeof n=="undefined")&&(l.close=1),e.maxHeight&&(l.maxHeight=e.maxHeight),e.maxWidth&&(l.maxWidth=e.maxWidth),a&&(l.highlight=a),s&&(l.borderhighlight=[s]),o&&(l.buttons=o.filter(c=>!c.disabled).map(c=>c.text));let u=await t.call("coc#float#create_dialog",[this.lines,l]);!u[1]||(this.bufnr=u[1],t.command("redraw",!0))}get winid(){return this.bufnr?this.nvim.call("bufwinid",[this.bufnr]):Promise.resolve(null)}dispose(){this.bufnr=void 0,z(this.disposables),this.disposables=[]}},HB=yD;var zB=S(W());var Nm=process.env.VIM_NODE_RPC=="1",bD=class{constructor(e,t,i){this.nvim=e;this.winid=t;this.bufnr=i}get valid(){return this.nvim.call("coc#float#valid",[this.winid]).then(e=>!!e)}close(){this.nvim.call("coc#float#close",[this.winid],!0)}refreshScrollbar(){Nm||this.nvim.call("coc#float#nvim_scrollbar",[this.winid],!0)}execute(e){this.nvim.call("coc#float#execute",[this.winid,e],!0)}click(e,t){let{nvim:i}=this;i.call("win_gotoid",[this.winid],!0),i.call("cursor",[e,t],!0),i.call("coc#float#nvim_float_click",[],!0)}async scrollForward(){let{nvim:e,bufnr:t,winid:i}=this,o=await e.createBuffer(t).length,s;if(Nm)s=await e.eval(`get(popup_getpos(${i}), 'lastline', 0)`);else{let a=await e.call("getwininfo",[i]);if(!a||!a.length)return;s=a[0].botline}s>=o||s==0||(e.pauseNotification(),this.setCursor(s-1),this.execute(`normal! ${s}Gzt`),this.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0))}async scrollBackward(){let{nvim:e,winid:t}=this,i;if(Nm)i=await e.eval(`get(popup_getpos(${t}), 'firstline', 0)`);else{let n=await e.call("getwininfo",[t]);if(!n||!n.length)return;i=n[0].topline}i!=1&&(e.pauseNotification(),this.setCursor(i-1),this.execute(`normal! ${i}Gzb`),this.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0))}setCursor(e){let{nvim:t,bufnr:i,winid:n}=this;Nm?t.call("win_execute",[n,`exe ${e+1}`],!0):(t.createWindow(n).notify("nvim_win_set_cursor",[[e+1,0]]),t.command(`sign unplace 6 buffer=${i}`,!0),t.command(`sign place 6 line=${e+1} name=CocCurrentLine buffer=${i}`,!0))}},qm=bD;var Upe=j()("model-menu"),wD=class{constructor(e,t,i){this.nvim=e;this.config=t;this.currIndex=0;this.disposables=[];this.keyMappings=new Map;this._onDidClose=new zB.Emitter;this.onDidClose=this._onDidClose.event;this.total=t.items.length,i&&i.onCancellationRequested(()=>{var n;(n=this.win)==null||n.close()}),this.disposables.push(this._onDidClose),this.addKeymappings()}attachEvents(){A.on("InputChar",this.onInputChar.bind(this),null,this.disposables),A.on("BufWinLeave",e=>{e==this.bufnr&&(this._onDidClose.fire(-1),this.bufnr=void 0,this.win=void 0,this.dispose())},null,this.disposables)}addKeymappings(){let{nvim:e}=this;this.addKeys(["",""],()=>{this._onDidClose.fire(-1),this.dispose()}),this.addKeys(["\r",""],()=>{this._onDidClose.fire(this.currIndex),this.dispose()});let t=o=>{var s;!this.win||(e.pauseNotification(),this.setCursor(o),(s=this.win)==null||s.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0))};this.addKeys("",async()=>{var o;await((o=this.win)==null?void 0:o.scrollForward())}),this.addKeys("",async()=>{var o;await((o=this.win)==null?void 0:o.scrollBackward())}),this.addKeys(["j","","",""],()=>{let o=this.currIndex==this.total-1?0:this.currIndex+1;t(o)}),this.addKeys(["k","","",""],()=>{let o=this.currIndex==0?this.total-1:this.currIndex-1;t(o)}),this.addKeys(["g"],()=>{t(0)}),this.addKeys(["G"],()=>{t(this.total-1)});let i,n;this.addKeys(["0","1","2","3","4","5","6","7","8","9"],o=>{i&&clearTimeout(i);let s=parseInt(o,10);if(!(isNaN(s)||s>this.total)&&!(n==null&&s==0)){if(n){let a=n*10+s;n=void 0,this._onDidClose.fire(a-1),this.dispose();return}if(this.total<10||s*10>this.total){this._onDidClose.fire(s-1),this.dispose();return}i=setTimeout(async()=>{this._onDidClose.fire(s-1),this.dispose()},200),n=s}})}async show(e={}){let{nvim:t}=this,{title:i,items:n}=this.config,o={};i&&(o.title=i),e.maxHeight&&(o.maxHeight=e.maxHeight),e.maxWidth&&(o.maxWidth=e.maxWidth),e.floatHighlight&&(o.highlight=e.floatHighlight),e.floatBorderHighlight&&(o.borderhighlight=[e.floatBorderHighlight]);let s=n.map((l,u)=>u<99?`${u+1}. ${l}`:l);e.confirmKey&&e.confirmKey!=""&&this.addKeys(e.confirmKey,()=>{this._onDidClose.fire(this.currIndex),this.dispose()});let a=await t.call("coc#float#create_menu",[s,o]);return this.win=new qm(t,a[0],a[1]),this.bufnr=a[1],this.attachEvents(),t.call("coc#prompt#start_prompt",["menu"],!0),a[0]}get buffer(){return this.bufnr?this.nvim.createBuffer(this.bufnr):void 0}dispose(){var e;z(this.disposables),this.disposables=[],this.nvim.call("coc#prompt#stop_prompt",["menu"],!0),(e=this.win)==null||e.close(),this.win=void 0}async onInputChar(e,t){if(e!="menu"||!this.win)return;let i=this.keyMappings.get(t);i?await Promise.resolve(i(t)):Upe.warn(`Ignored key press: ${t}`)}setCursor(e){!this.win||(this.currIndex=e,this.win.setCursor(e))}addKeys(e,t){if(Array.isArray(e))for(let i of e)this.keyMappings.set(i,t);else this.keyMappings.set(e,t)}},GB=wD;var VB=process.env.VIM_NODE_RPC=="1",PRe=j()("model-notification"),xD=class{constructor(e,t,i=!0){this.nvim=e;this.config=t;this.disposables=[];this._disposed=!1;i&&(A.on("BufWinLeave",n=>{n==this.bufnr&&(this.dispose(),t.callback&&t.callback(-1))},null,this.disposables),A.on("FloatBtnClick",(n,o)=>{if(n==this.bufnr){this.dispose();let s=t==null?void 0:t.buttons.filter(a=>a.disabled!=!0);t.callback&&t.callback(s[o].index)}},null,this.disposables))}get lines(){return this.config.content.split(/\r?\n/)}async show(e){let{nvim:t}=this,{title:i,close:n,timeout:o,buttons:s,borderhighlight:a}=this.config,l=Object.assign({},e);l.close=n?1:0,i&&(l.title=i),a&&(l.borderhighlight=a),s&&(l.buttons=s.filter(c=>!c.disabled).map(c=>c.text)),o&&(l.timeout=o);let u=await t.call("coc#float#create_notification",[this.lines,l]);return u?(this._disposed?(this.nvim.call("coc#float#close",[u[0]],!0),VB&&this.nvim.command("redraw",!0)):(this._winid=u[0],this.bufnr=u[1]),this._winid!=null):!1}get winid(){return this._winid}dispose(){if(this._disposed)return;this._disposed=!0;let{winid:e}=this;e&&(this.nvim.call("coc#float#close",[e],!0),VB&&this.nvim.command("redraw",!0)),this.bufnr=void 0,this._winid=void 0,z(this.disposables),this.disposables=[]}},qf=xD;var KB=S(W());var Wpe=j()("model-dialog"),JB=process.env.VIM_NODE_RPC=="1",DD=class{constructor(e,t,i){this.nvim=e;this.config=t;this.picked=new Set;this.currIndex=0;this.disposables=[];this.keyMappings=new Map;this._onDidClose=new KB.Emitter;this.onDidClose=this._onDidClose.event;for(let n=0;n{var n;(n=this.win)==null||n.close()}),this.disposables.push(this._onDidClose),this.addKeymappings()}attachEvents(){A.on("InputChar",this.onInputChar.bind(this),null,this.disposables),A.on("BufWinLeave",e=>{e==this.bufnr&&(this._onDidClose.fire(void 0),this.bufnr=void 0,this.win=void 0,this.dispose())},null,this.disposables),A.on("FloatBtnClick",(e,t)=>{if(e==this.bufnr){if(t==0){let i=Array.from(this.picked);this._onDidClose.fire(i.length?i:void 0)}else this._onDidClose.fire(void 0);this.dispose()}},null,this.disposables)}addKeymappings(){let{nvim:e}=this,t=n=>{this.picked.has(n)?this.picked.delete(n):this.picked.add(n)};this.addKeys("",async()=>{if(JB||!this.win)return;let[n,o,s]=await e.eval("[v:mouse_winid,v:mouse_lnum,v:mouse_col]");if(global.hasOwnProperty("__TEST__")){let a=await e.getVar("mouse_position");n=a[0],o=a[1],s=a[2]}e.pauseNotification(),n==this.win.winid&&(s<=3?(t(o-1),this.changeLine(o-1)):this.setCursor(o-1)),e.call("win_gotoid",[n],!0),e.call("cursor",[o,s],!0),e.call("coc#float#nvim_float_click",[],!0),e.command("redraw",!0),await e.resumeNotification()}),this.addKeys(["",""],()=>{this._onDidClose.fire(void 0),this.dispose()}),this.addKeys("",()=>{if(this.picked.size==0)this._onDidClose.fire(void 0);else{let n=Array.from(this.picked);this._onDidClose.fire(n)}this.dispose()});let i=n=>{e.pauseNotification(),this.setCursor(n),this.win.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0)};this.addKeys(["j","","",""],()=>{let n=this.currIndex==this.total-1?0:this.currIndex+1;i(n)}),this.addKeys(["k","","",""],()=>{let n=this.currIndex==0?this.total-1:this.currIndex-1;i(n)}),this.addKeys(["g"],()=>{i(0)}),this.addKeys(["G"],()=>{i(this.total-1)}),this.addKeys(" ",async()=>{let n=this.currIndex;t(n),e.pauseNotification(),this.changeLine(n),this.currIndex!=this.total-1&&this.setCursor(this.currIndex+1),e.command("redraw",!0),await e.resumeNotification()}),this.addKeys("",async()=>{var n;await((n=this.win)==null?void 0:n.scrollForward())}),this.addKeys("",async()=>{var n;await((n=this.win)==null?void 0:n.scrollBackward())})}async show(e={}){let{nvim:t}=this,{title:i,items:n}=this.config,o={close:1,cursorline:1};if(e.maxHeight&&(o.maxHeight=e.maxHeight),e.maxWidth&&(o.maxWidth=e.maxWidth),i&&(o.title=i),o.close=1,o.cursorline=1,e.floatHighlight&&(o.highlight=e.floatHighlight),e.floatBorderHighlight&&(o.borderhighlight=[e.floatBorderHighlight]),e.pickerButtons){let c=e.pickerButtonShortcut;o.buttons=["Submit"+(c?" ":""),"Cancel"+(c?" ":"")]}e.confirmKey&&e.confirmKey!=""&&this.addKeys(e.confirmKey,()=>{this._onDidClose.fire(void 0),this.dispose()});let s=[],a=[];for(let c=0;c{i==this.bufnr&&(this.tokenSource&&this.tokenSource.cancel(),this.dispose())},null,this.disposables)}async show(e){let{task:t}=this.option,i=this.tokenSource=new XB.CancellationTokenSource;this.disposables.push(i);let n=0;return await new Promise((s,a)=>{i.token.onCancellationRequested(()=>{s(void 0)}),super.show(Object.assign({minWidth:e.minProgressWidth||30,progress:1},e)).then(l=>{l||a(new Error("Failed to create float window"))}).catch(a),t({report:l=>{if(!this.bufnr)return;let u="";l.message&&(u+=l.message.replace(/\r?\n/g," ")),l.increment&&(n+=l.increment,u=u+(u.length?` ${n}%`:`${n}%`)),this.nvim.call("setbufline",[this.bufnr,2,u],!0)}},i.token).then(l=>{this._disposed||(setTimeout(()=>{this.dispose()},100),s(l))},l=>{this._disposed||(this.dispose(),l instanceof Error?a(l):s(void 0))})})}dispose(){super.dispose(),this.tokenSource=void 0}},ZB=SD;var QB=S(require("crypto"));function $f(){return QB.default.randomBytes(16)}var e3=[];for(var $m=0;$m<256;++$m)e3[$m]=($m+256).toString(16).substr(1);function Hpe(r,e){var t=e||0,i=e3;return[i[r[t++]],i[r[t++]],i[r[t++]],i[r[t++]],"-",i[r[t++]],i[r[t++]],"-",i[r[t++]],i[r[t++]],"-",i[r[t++]],i[r[t++]],"-",i[r[t++]],i[r[t++]],i[r[t++]],i[r[t++]],i[r[t++]],i[r[t++]]].join("")}var Bm=Hpe;var t3,ED,CD=0,_D=0;function zpe(r,e,t){var i=e&&t||0,n=e||[];r=r||{};var o=r.node||t3,s=r.clockseq!==void 0?r.clockseq:ED;if(o==null||s==null){var a=r.random||(r.rng||$f)();o==null&&(o=t3=[a[0]|1,a[1],a[2],a[3],a[4],a[5]]),s==null&&(s=ED=(a[6]<<8|a[7])&16383)}var l=r.msecs!==void 0?r.msecs:new Date().getTime(),u=r.nsecs!==void 0?r.nsecs:_D+1,c=l-CD+(u-_D)/1e4;if(c<0&&r.clockseq===void 0&&(s=s+1&16383),(c<0||l>CD)&&r.nsecs===void 0&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");CD=l,_D=u,ED=s,l+=122192928e5;var f=((l&268435455)*1e4+u)%4294967296;n[i++]=f>>>24&255,n[i++]=f>>>16&255,n[i++]=f>>>8&255,n[i++]=f&255;var p=l/4294967296*1e4&268435455;n[i++]=p>>>8&255,n[i++]=p&255,n[i++]=p>>>24&15|16,n[i++]=p>>>16&255,n[i++]=s>>>8|128,n[i++]=s&255;for(var d=0;d<6;++d)n[i+d]=o[d];return e||Bm(n)}var qo=zpe;function Gpe(r,e,t){var i=e&&t||0;typeof r=="string"&&(e=r==="binary"?new Array(16):null,r=null),r=r||{};var n=r.random||(r.rng||$f)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e)for(var o=0;o<16;++o)e[i+o]=n[o];return e||Bm(n)}var he=Gpe;var YRe=j()("model-status"),PD=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],TD=class{constructor(e){this.nvim=e;this.items=new Map;this.shownIds=new Set;this._text="";this.interval=setInterval(()=>{this.setStatusText().logError()},100)}dispose(){clearInterval(this.interval)}createStatusBarItem(e=0,t=!1){let i=qo(),n={text:"",priority:e,isProgress:t,show:()=>{this.shownIds.add(i)},hide:()=>{this.shownIds.delete(i)},dispose:()=>{this.shownIds.delete(i),this.items.delete(i)}};return this.items.set(i,n),n}getText(){if(this.shownIds.size==0)return"";let e=new Date,t=Math.floor(e.getMilliseconds()/100),i="",n=[];for(let[o,s]of this.items)this.shownIds.has(o)&&n.push(s);n.sort((o,s)=>o.priority-s.priority);for(let o of n)o.isProgress?i=`${i} ${PD[t]} ${o.text}`:i=`${i} ${o.text}`;return i}async setStatusText(){let e=this.getText(),{nvim:t}=this;e!=this._text&&(this._text=e,t.pauseNotification(),this.nvim.setVar("coc_status",e,!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0),await t.resumeNotification(!1,!0))}},r3=TD;var Kr;(function(r){r[r.Buffer=0]="Buffer",r[r.LanguageServer=1]="LanguageServer",r[r.Global=2]="Global"})(Kr||(Kr={}));var Jr;(function(r){r[r.Global=0]="Global",r[r.Local=1]="Local",r[r.SingleFile=2]="SingleFile",r[r.Internal=3]="Internal"})(Jr||(Jr={}));var Yr;(function(r){r[r.Native=0]="Native",r[r.Remote=1]="Remote",r[r.Service=2]="Service"})(Yr||(Yr={}));var gn;(function(r){r[r.More=0]="More",r[r.Warning=1]="Warning",r[r.Error=2]="Error"})(gn||(gn={}));var pt;(function(r){r[r.Global=0]="Global",r[r.User=1]="User",r[r.Workspace=2]="Workspace"})(pt||(pt={}));var ye;(function(r){r[r.Initial=0]="Initial",r[r.Starting=1]="Starting",r[r.StartFailed=2]="StartFailed",r[r.Running=3]="Running",r[r.Stopping=4]="Stopping",r[r.Stopped=5]="Stopped"})(ye||(ye={}));var qj=S(o3()),$j=S(Bl()),Dt=S($i()),Qi=S(require("os")),ke=S(require("path"));var le=S(W());var Bj=S(El());var GD=S(require("os")),jo=S(require("fs")),Xi=S(require("path")),VD=S(W());var w3=S(W());"use strict";var m3=function(){function r(e,t,i,n){this._uri=e,this._languageId=t,this._version=i,this._content=n,this._lineOffsets=void 0}return Object.defineProperty(r.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"version",{get:function(){return this._version},enumerable:!0,configurable:!0}),r.prototype.getText=function(e){if(e){var t=this.offsetAt(e.start),i=this.offsetAt(e.end);return this._content.substring(t,i)}return this._content},r.prototype.update=function(e,t){for(var i=0,n=e;ie?n=o:i=o+1}var s=i-1;return{line:s,character:e-t[s]}},r.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var i=t[e.line],n=e.line+1l&&u.push(s.substring(l,d)),p.newText.length&&u.push(p.newText),l=n.offsetAt(p.range.end)}return u.push(s.substr(l)),u.join("")}r.applyEdits=i})(kt||(kt={}));function FD(r,e){if(r.length<=1)return r;var t=r.length/2|0,i=r.slice(0,t),n=r.slice(t);FD(i,e),FD(n,e);for(var o=0,s=0,a=0;ot.line||e.line===t.line&&e.character>t.character?{start:t,end:e}:r}function rde(r){var e=h3(r.range);return e!==r.range?{newText:r.newText,range:e}:r}"use strict";function Uf(r,e){e===void 0&&(e=!1);var t=r.length,i=0,n="",o=0,s=16,a=0,l=0,u=0,c=0,f=0;function p(w,E){for(var P=0,k=0;P=48&&_<=57)k=k*16+_-48;else if(_>=65&&_<=70)k=k*16+_-65+10;else if(_>=97&&_<=102)k=k*16+_-97+10;else break;i++,P++}return P=t){w+=r.substring(E,i),f=2;break}var P=r.charCodeAt(i);if(P===34){w+=r.substring(E,i),i++;break}if(P===92){if(w+=r.substring(E,i),i++,i>=t){f=2;break}var k=r.charCodeAt(i++);switch(k){case 34:w+='"';break;case 92:w+="\\";break;case 47:w+="/";break;case 98:w+="\b";break;case 102:w+="\f";break;case 110:w+=` +`;break;case 114:w+="\r";break;case 116:w+=" ";break;case 117:var _=p(4,!0);_>=0?w+=String.fromCharCode(_):f=4;break;default:f=5}E=i;continue}if(P>=0&&P<=31)if(jf(P)){w+=r.substring(E,i),f=2;break}else f=6;i++}return w}function y(){if(n="",f=0,o=i,l=a,c=u,i>=t)return o=t,s=17;var w=r.charCodeAt(i);if(AD(w)){do i++,n+=String.fromCharCode(w),w=r.charCodeAt(i);while(AD(w));return s=15}if(jf(w))return i++,n+=String.fromCharCode(w),w===13&&r.charCodeAt(i)===10&&(i++,n+=` +`),a++,u=i,s=14;switch(w){case 123:return i++,s=1;case 125:return i++,s=2;case 91:return i++,s=3;case 93:return i++,s=4;case 58:return i++,s=6;case 44:return i++,s=5;case 34:return i++,n=m(),s=10;case 47:var E=i-1;if(r.charCodeAt(i+1)===47){for(i+=2;i=12&&w<=15);return w}return{setPosition:d,getPosition:function(){return i},scan:e?x:y,getToken:function(){return s},getTokenValue:function(){return n},getTokenOffset:function(){return o},getTokenLength:function(){return i-o},getTokenStartLine:function(){return l},getTokenStartCharacter:function(){return o-c},getTokenError:function(){return f}}}function AD(r){return r===32||r===9||r===11||r===12||r===160||r===5760||r>=8192&&r<=8203||r===8239||r===8287||r===12288||r===65279}function jf(r){return r===10||r===13||r===8232||r===8233}function jl(r){return r>=48&&r<=57}"use strict";function LD(r,e,t){var i,n,o,s,a;if(e){for(s=e.offset,a=s+e.length,o=s;o>0&&!Wf(r,o-1);)o--;for(var l=a;ls&&r.substring(F,q)!==R&&v.push({offset:F,length:q-F,content:R})}var w=y();if(w!==17){var E=d.getTokenOffset()+o,P=OD(p,i);x(P,o,E)}for(;w!==17;){for(var k=d.getTokenOffset()+d.getTokenLength()+o,_=y(),O="";!c&&(_===12||_===13);){var I=d.getTokenOffset()+o;x(" ",k,I),k=d.getTokenOffset()+d.getTokenLength()+o,O=_===12?m():"",_=y()}if(_===2)w!==1&&(f--,O=m());else if(_===4)w!==3&&(f--,O=m());else{switch(w){case 3:case 1:f++,O=m();break;case 5:case 12:O=m();break;case 13:c?O=m():O=" ";break;case 6:O=" ";break;case 10:if(_===6){O="";break}case 7:case 8:case 9:case 11:case 2:case 4:_===12||_===13?O=" ":_!==5&&_!==17&&(h=!0);break;case 16:h=!0;break}c&&(_===12||_===13)&&(O=m())}var L=d.getTokenOffset()+o;x(O,k,L),w=_}return v}function OD(r,e){for(var t="",i=0;i=t.children.length)return;t=t.children[c]}}return t}}function MD(r,e,t){t===void 0&&(t=Hf.DEFAULT);var i=Uf(r,!1);function n(I){return I?function(){return I(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter())}:function(){return!0}}function o(I){return I?function(L){return I(L,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter())}:function(){return!0}}var s=n(e.onObjectBegin),a=o(e.onObjectProperty),l=n(e.onObjectEnd),u=n(e.onArrayBegin),c=n(e.onArrayEnd),f=o(e.onLiteralValue),p=o(e.onSeparator),d=n(e.onComment),h=o(e.onError),m=t&&t.disallowComments,y=t&&t.allowTrailingComma;function v(){for(;;){var I=i.scan();switch(i.getTokenError()){case 4:x(14);break;case 5:x(15);break;case 3:x(13);break;case 1:m||x(11);break;case 2:x(12);break;case 6:x(16);break}switch(I){case 12:case 13:m?x(10):d();break;case 16:x(1);break;case 15:case 14:break;default:return I}}}function x(I,L,R){if(L===void 0&&(L=[]),R===void 0&&(R=[]),h(I),L.length+R.length>0)for(var F=i.getToken();F!==17;){if(L.indexOf(F)!==-1){v();break}else if(R.indexOf(F)!==-1)break;F=v()}}function w(I){var L=i.getTokenValue();return I?f(L):a(L),v(),!0}function E(){switch(i.getToken()){case 11:var I=i.getTokenValue(),L=Number(I);isNaN(L)&&(x(2),L=0),f(L);break;case 7:f(null);break;case 8:f(!0);break;case 9:f(!1);break;default:return!1}return v(),!0}function P(){return i.getToken()!==10?(x(3,[],[2,5]),!1):(w(!1),i.getToken()===6?(p(":"),v(),O()||x(4,[],[2,5])):x(5,[],[2,5]),!0)}function k(){s(),v();for(var I=!1;i.getToken()!==2&&i.getToken()!==17;){if(i.getToken()===5){if(I||x(4,[],[]),p(","),v(),i.getToken()===2&&y)break}else I&&x(6,[],[]);P()||x(4,[],[2,5]),I=!0}return l(),i.getToken()!==2?x(7,[2],[]):v(),!0}function _(){u(),v();for(var I=!1;i.getToken()!==4&&i.getToken()!==17;){if(i.getToken()===5){if(I||x(4,[],[]),p(","),v(),i.getToken()===4&&y)break}else I&&x(6,[],[]);O()||x(4,[],[4,5]),I=!0}return c(),i.getToken()!==4?x(8,[4],[]):v(),!0}function O(){switch(i.getToken()){case 3:return _();case 1:return k();case 10:return w(!0);default:return E()}}return v(),i.getToken()===17?t.allowEmptyContent?!0:(x(4,[],[]),!1):O()?(i.getToken()!==17&&x(9,[],[]),!0):(x(4,[],[]),!1)}function ode(r){switch(typeof r){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(r){if(Array.isArray(r))return"array"}else return"null";return"object"}default:return"null"}}"use strict";function v3(r,e,t,i){for(var n,o=e.slice(),s=[],a=ND(r,s),l=void 0,u=void 0;o.length>0&&(u=o.pop(),l=Wm(a,o),l===void 0&&t!==void 0);)typeof u=="string"?t=(n={},n[u]=t,n):t=[t];if(l)if(l.type==="object"&&typeof u=="string"&&Array.isArray(l.children)){var c=Wm(l,[u]);if(c!==void 0)if(t===void 0){if(!c.parent)throw new Error("Malformed AST");var f=l.children.indexOf(c.parent),p=void 0,d=c.parent.offset+c.parent.length;if(f>0){var h=l.children[f-1];p=h.offset+h.length}else if(p=l.offset+1,l.children.length>1){var m=l.children[1];d=m.offset}return Zs(r,{offset:p,length:d-p,content:""},i)}else return Zs(r,{offset:c.offset,length:c.length,content:JSON.stringify(t)},i);else{if(t===void 0)return[];var y=JSON.stringify(u)+": "+JSON.stringify(t),v=i.getInsertionIndex?i.getInsertionIndex(l.children.map(function(I){return I.children[0].value})):l.children.length,x=void 0;if(v>0){var h=l.children[v-1];x={offset:h.offset+h.length,length:0,content:","+y}}else l.children.length===0?x={offset:l.offset+1,length:0,content:y}:x={offset:l.offset+1,length:0,content:y+","};return Zs(r,x,i)}}else if(l.type==="array"&&typeof u=="number"&&Array.isArray(l.children)){var w=u;if(w===-1){var y=""+JSON.stringify(t),x=void 0;if(l.children.length===0)x={offset:l.offset+1,length:0,content:y};else{var h=l.children[l.children.length-1];x={offset:h.offset+h.length,length:0,content:","+y}}return Zs(r,x,i)}else if(t===void 0&&l.children.length>=0){var E=u,P=l.children[E],x=void 0;if(l.children.length===1)x={offset:l.offset+1,length:l.length-2,content:""};else if(l.children.length-1===E){var h=l.children[E-1],k=h.offset+h.length,_=l.offset+l.length;x={offset:k,length:_-2-k,content:""}}else x={offset:P.offset,length:l.children[E+1].offset-P.offset,content:""};return Zs(r,x,i)}else if(t!==void 0){var x=void 0,y=""+JSON.stringify(t);if(!i.isArrayInsertion&&l.children.length>u){var O=l.children[u];x={offset:O.offset,length:O.length,content:y}}else if(l.children.length===0||u===0)x={offset:l.offset+1,length:0,content:l.children.length===0?y:y+","};else{var v=u>l.children.length?l.children.length:u,h=l.children[v-1];x={offset:h.offset+h.length,length:0,content:","+y}}return Zs(r,x,i)}else throw new Error("Can not "+(t===void 0?"remove":i.isArrayInsertion?"insert":"modify")+" Array index "+w+" as length is not sufficient")}else throw new Error("Can not add "+(typeof u!="number"?"index":"property")+" to parent of type "+l.type);else{if(t===void 0)throw new Error("Can not delete in empty document");return Zs(r,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(t)},i)}}function Zs(r,e,t){if(!t.formattingOptions)return[e];var i=Hm(r,e),n=e.offset,o=e.offset+e.content.length;if(e.length===0||e.content.length===0){for(;n>0&&!Wf(i,n-1);)n--;for(;o=0;a--){var l=s[a];i=Hm(i,l),n=Math.min(n,l.offset),o=Math.max(o,l.offset+l.length),o+=l.content.length-l.length}var u=r.length-(i.length-o)-n;return[{offset:n,length:u,content:i.substring(n,o)}]}function Hm(r,e){return r.substring(0,e.offset)+e.content+r.substring(e.offset+e.length)}"use strict";var Ul=g3;function y3(r,e,t,i){return v3(r,e,t,i)}function b3(r,e){for(var t=e.length-1;t>=0;t--)r=Hm(r,e[t]);return r}var zf=S(require("fs"));var zm=S(require("path")),sde=j()("configuration-util"),ade=zm.dirname(__dirname);function x3(r,e){if(!r||!zf.default.existsSync(r))return{contents:{}};let t,i=$.file(r).toString();try{t=zf.default.readFileSync(r,"utf8")}catch(s){t=""}let[n,o]=lde(t);return n&&n.length&&e(ude(i,t,n)),{contents:o}}function lde(r){if(r.length==0)return[[],{}];let e=[],t=Ul(r,e,{allowTrailingComma:!0});function i(o,s,a,l){if(a.length==0)o[s]=n(l);else{o[s]||(o[s]={});let u=o[s],c=a.shift();i(u,c,a,l)}}function n(o,s=!1){if(!wt(o))return o;if(fm(o))return{};let a={};for(let l of Object.keys(o))if(s&&l.includes(".")){let u=l.split("."),c=u.shift();i(a,c,u,o[l])}else a[l]=n(o[l]);return a}return[e,n(t,!0)]}function ude(r,e,t){let i=[],n=kt.create(r,"json",0,e);for(let o of t){let s="parse error";switch(o.error){case 2:s="invalid number";break;case 8:s="close brace expected";break;case 5:s="colon expected";break;case 6:s="comma expected";break;case 9:s="end of file expected";break;case 16:s="invaliad character";break;case 10:s="invalid commment token";break;case 15:s="invalid escape character";break;case 1:s="invalid symbol";break;case 14:s="invalid unicode";break;case 3:s="property name expected";break;case 13:s="unexpected end of number";break;case 12:s="unexpected end of string";break;case 11:s="unexpected end of comment";break;case 4:s="value expected";break;default:s="Unknwn error";break}let a={start:n.positionAt(o.offset),end:n.positionAt(o.offset+o.length)},l=w3.Location.create(r,a);i.push({location:l,message:s})}return i}function Gf(r,e,t,i){let n=e.split("."),o=n.pop(),s=r;for(let a=0;a{let o=t[n].default;o!==void 0&&Gf(i,n,o,s=>{sde.error(s)})}),{contents:i}}function qD(r,e){let t=[];for(let i of Object.keys(r)){let n=r[i],o=e?`${e}.${i}`:i;t.push(o),wt(n)&&t.push(...qD(n,o))}return t}function C3(r,e){let t=[],i=qD(r),n=qD(e),o=n.filter(a=>!i.includes(a)),s=i.filter(a=>!n.includes(a));t.push(...o),t.push(...s);for(let a of i){if(!n.includes(a))continue;let l=Gm(r,a),u=Gm(e,a);Ne(l,u)||t.push(a)}return t}var Fr=class{constructor(e={}){this._contents=e}get contents(){return this._contents}clone(){return new Fr(zn(this._contents))}getValue(e){return e?Gm(this.contents,e):this.contents}merge(...e){let t=zn(this.contents);for(let i of e)this.mergeContents(t,i.contents);return new Fr(t)}freeze(){return Object.isFrozen(this._contents)||Object.freeze(this._contents),this}mergeContents(e,t){for(let i of Object.keys(t)){if(i in e&&wt(e[i])&&wt(t[i])){this.mergeContents(e[i],t[i]);continue}e[i]=zn(t[i])}}setValue(e,t){Gf(this.contents,e,t,i=>{console.error(i)})}removeValue(e){S3(this.contents,e)}};var Vm=class{constructor(e,t,i,n=new Fr){this._defaultConfiguration=e;this._userConfiguration=t;this._workspaceConfiguration=i;this._memoryConfiguration=n}getConsolidateConfiguration(){return this._consolidateConfiguration||(this._consolidateConfiguration=this._defaultConfiguration.merge(this._userConfiguration,this._workspaceConfiguration,this._memoryConfiguration),this._consolidateConfiguration=this._consolidateConfiguration.freeze()),this._consolidateConfiguration}getValue(e){return this.getConsolidateConfiguration().getValue(e)}inspect(e){let t=this.getConsolidateConfiguration(),{_workspaceConfiguration:i,_memoryConfiguration:n}=this;return{default:this._defaultConfiguration.freeze().getValue(e),user:this._userConfiguration.freeze().getValue(e),workspace:i.freeze().getValue(e),memory:n.freeze().getValue(e),value:t.getValue(e)}}get defaults(){return this._defaultConfiguration}get user(){return this._userConfiguration}get workspace(){return this._workspaceConfiguration}toData(){return{defaults:{contents:this._defaultConfiguration.contents},user:{contents:this._userConfiguration.contents},workspace:{contents:this._workspaceConfiguration.contents}}}};var Ide=S(require("child_process")),Ci=S($i()),Fde=S(require("net")),HD=S(require("os")),Xr=S(require("path")),zD=S(require("readline")),Ade=S(require("util")),V3=S(Qs()),$1e=j()("util-fs");async function Ht(r){let e=null;try{e=await Ci.default.stat(r)}catch(t){}return e}function K3(r,e){return new Promise((t,i)=>{Ci.default.rename(r,e,n=>{if(n)return i(n);t()})})}function Jf(r,e,t,i=!1,n=!0){let o=HD.default.homedir(),s=Kf(r);if(Ye(s,o,!0))return null;if(n&&t&&Ye(t,s,!0)&&Bo(t,e))return t;let a=s.split(Xr.default.sep);if(i){for(;a.length>0;){let l=a.join(Xr.default.sep);if(l==o)break;if(l!=o&&Bo(l,e))return l;a.pop()}return null}else{let l=[a.shift()];for(let u of a){l.push(u);let c=l.join(Xr.default.sep);if(c!=o&&Bo(c,e))return c}return null}}function Bo(r,e){try{let t=Ci.default.readdirSync(r);for(let i of e)if(i.includes("*")?V3.default.match(t,i,{nobrace:!0,noext:!0,nocomment:!0,nonegate:!0,dot:!0}).length!==0:t.includes(i))return!0}catch(t){}return!1}function Hl(r,e){let t=Xr.default.parse(e).root,i=Array.isArray(r)?r:[r];for(;e&&e!==t;){if(Bo(e,i))for(let o of i){let s=Xr.default.join(e,o);if(Ci.default.existsSync(s))return s}e=Xr.default.dirname(e)}return null}function Yf(r,e){return new Promise((t,i)=>{Ci.default.readFile(r,e,(n,o)=>{n&&i(n),t(o)})})}function J3(r){let e,t=0;return new Promise((i,n)=>{Ci.default.createReadStream(r).on("error",o=>n(o)).on("data",o=>{for(e=0;ei(t))})}function Y3(r,e,t){if(!Ci.default.existsSync(r))return Promise.reject(new Error(`file does not exist: ${r}`));let i=[],n=zD.default.createInterface({input:Ci.default.createReadStream(r,{encoding:"utf8"}),crlfDelay:Infinity,terminal:!1}),o=0;return new Promise((s,a)=>{n.on("line",l=>{o==0&&l.startsWith("\uFEFF")&&(l=l.slice(1)),o>=e&&o<=t&&i.push(l),o==t&&n.close(),o=o+1}),n.on("close",()=>{s(i)}),n.on("error",a)})}function X3(r,e){if(!Ci.default.existsSync(r))return Promise.reject(new Error(`file does not exist: ${r}`));let t=zD.default.createInterface({input:Ci.default.createReadStream(r,{encoding:"utf8"}),crlfDelay:Infinity,terminal:!1}),i=0;return new Promise((n,o)=>{t.on("line",s=>{if(i==e){i==0&&s.startsWith("\uFEFF")&&(s=s.slice(1)),t.close(),n(s);return}i=i+1}),t.on("error",o)})}async function Z3(r,e){await Ci.default.writeFile(r,e,{encoding:"utf8"})}function Jm(r){return r.startsWith("file:")}function Ye(r,e,t=!1){let i=Kf(Xr.default.resolve(Xr.default.normalize(r))),n=Kf(Xr.default.resolve(Xr.default.normalize(e)));return i=="//"&&(i="/"),i==n?!!t:i.endsWith(Xr.default.sep)?n.startsWith(i):n.startsWith(i)&&n[i.length]==Xr.default.sep}function Kf(r){return HD.default.platform()!="win32"||r[1]!=":"?r:r[0].toUpperCase()+r.slice(1)}var Ode=j()("configurations");function KD(r,e){if(e){if(r&&r.hasOwnProperty(e))return r[e];let t=e.split("."),i=r;for(let n=0;i&&nn.location.uri!=t);let i=x3(e,n=>{this._errorItems.push(...n)});return this._onError.fire(this._errorItems),i}get errorItems(){return this._errorItems}get foldConfigurations(){return this._folderConfigurations}extendsDefaults(e){let{defaults:t}=this._configuration,{contents:i}=t;i=zn(i),Object.keys(e).forEach(o=>{Gf(i,o,e[o],s=>{Ode.error(s)})});let n={defaults:{contents:i},user:this._configuration.user,workspace:this._configuration.workspace};this._configuration=ea.parse(n)}updateUserConfig(e){if(!e||Object.keys(e).length==0)return;let{user:t}=this._configuration,i=t.clone();Object.keys(e).forEach(n=>{let o=e[n];if(o===void 0)i.removeValue(n);else if(wt(o))for(let s of Object.keys(o))i.setValue(`${n}.${s}`,o[s]);else i.setValue(n,o)}),this.changeConfiguration(pt.User,i)}get defaults(){return this._configuration.defaults}get user(){return this._configuration.user}get workspace(){return this._configuration.workspace}addFolderFile(e){let{_folderConfigurations:t}=this;if(t.has(e)||Xi.default.resolve(e,"../..")==GD.default.homedir())return;let i=this.parseContentFromFile(e);this.watchFile(e,pt.Workspace),this.changeConfiguration(pt.Workspace,i,e)}watchFile(e,t){if(!jo.default.existsSync(e)||global.hasOwnProperty("__TEST__"))return;let i=Pl(e,()=>{let n=this.parseContentFromFile(e);this.changeConfiguration(t,n,e)});this.disposables.push(i)}changeConfiguration(e,t,i){let{defaults:n,user:o,workspace:s}=this._configuration,{workspaceConfigFile:a}=this,l={defaults:e==pt.Global?t:n,user:e==pt.User?t:o,workspace:e==pt.Workspace?t:s},u=ea.parse(l),c=C3(this._configuration.getValue(),u.getValue());e==pt.Workspace&&i&&(this._folderConfigurations.set(i,new Fr(t.contents)),this.workspaceConfigFile=i),c.length!=0&&(this._configuration=u,this._onChange.fire({affectsConfiguration:(f,p)=>{if(!p||e!=pt.Workspace)return c.includes(f);let d=$.parse(p);if(d.scheme!=="file")return c.includes(f);let h=d.fsPath,m=a?Xi.default.resolve(a,"../.."):"";return i&&!Ye(m,h,!0)&&!Ye(Xi.default.resolve(i,"../.."),h)?!1:c.includes(f)}}))}setFolderConfiguration(e){let t=$.parse(e);if(t.scheme!="file")return;let i=t.fsPath;for(let[n,o]of this.foldConfigurations){let s=Xi.default.resolve(n,"../..");if(Ye(s,i,!0)&&this.workspaceConfigFile!=n){this.changeConfiguration(pt.Workspace,o,n);break}}}hasFolderConfiguration(e){let{folders:t}=this;return t.findIndex(i=>Ye(i,e,!0))!==-1}getConfigFile(e){return e==pt.Global?null:e==pt.User?this.userConfigFile:this.workspaceConfigFile}get folders(){let e=[],{_folderConfigurations:t}=this;for(let i of t.keys())e.push(Xi.default.resolve(i,"../.."));return e}get configuration(){return this._configuration}getConfiguration(e,t){let i;if(t){let{defaults:s,user:a}=this._configuration;i=new Vm(s,a,this.getFolderConfiguration(t))}else i=this._configuration;let n=Object.freeze(KD(i.getValue(null),e)),o={has(s){return typeof KD(n,s)!="undefined"},get:(s,a)=>{let l=KD(n,s);return l==null?a:l},update:(s,a,l=!1)=>{let u=e?`${e}.${s}`:s,c=l?pt.User:pt.Workspace,f=c==pt.User?this.user.clone():this.workspace.clone();if(a==null?f.removeValue(u):f.setValue(u,a),c==pt.Workspace&&!this.workspaceConfigFile&&this._proxy){let p=this.workspaceConfigFile=this._proxy.workspaceConfigFile;if(!jo.default.existsSync(p)){let d=Xi.default.dirname(p);jo.default.existsSync(d)||jo.default.mkdirSync(d),jo.default.writeFileSync(p,"{}",{encoding:"utf8"})}}this.changeConfiguration(c,f,c==pt.Workspace?this.workspaceConfigFile:this.userConfigFile),this._proxy&&!global.hasOwnProperty("__TEST__")&&(a==null?this._proxy.$removeConfigurationOption(c,u):this._proxy.$updateConfigurationOption(c,u,a))},inspect:s=>{s=e?`${e}.${s}`:s;let a=this._configuration.inspect(s);if(a)return{key:s,defaultValue:a.default,globalValue:a.user,workspaceValue:a.workspace}}};return Object.defineProperty(o,"has",{enumerable:!1}),Object.defineProperty(o,"get",{enumerable:!1}),Object.defineProperty(o,"update",{enumerable:!1}),Object.defineProperty(o,"inspect",{enumerable:!1}),typeof n=="object"&&Ax(o,n,!1),fq(o)}getFolderConfiguration(e){let t=$.parse(e);if(t.scheme!="file")return new Fr;let i=t.fsPath;for(let[n,o]of this.foldConfigurations){let s=Xi.default.resolve(n,"../..");if(Ye(s,i,!0))return o}return new Fr}checkFolderConfiguration(e){let t=$.parse(e);if(t.scheme!="file")return;let i=Xi.default.dirname(t.fsPath);if(this.hasFolderConfiguration(i))this.setFolderConfiguration(e);else{let n=Hl(".vim",i);if(n&&n!=GD.default.homedir()){let o=Xi.default.join(n,Gi);jo.default.existsSync(o)&&this.addFolderFile(o)}}}static parse(e){let t=new Fr(e.defaults.contents),i=new Fr(e.user.contents),n=new Fr(e.workspace.contents);return new Vm(t,i,n,new Fr)}dispose(){z(this.disposables)}},Q3=ea;var JD=S(require("fs"));var YD=S(require("path"));var uke=j()("configuration-shape"),XD=class{constructor(e){this.workspace=e}get nvim(){return this.workspace.nvim}async modifyConfiguration(e,t,i){let{nvim:n,workspace:o}=this,s=o.getConfigFile(e);if(!s)return;let a={tabSize:2,insertSpaces:!0},l=JD.default.readFileSync(s,"utf8");i=i==null?void 0:i;let u=y3(l,[t],i,{formattingOptions:a});l=b3(l,u),JD.default.writeFileSync(s,l,"utf8"),o.getDocument($.file(s).toString())&&n.command("checktime",!0)}get workspaceConfigFile(){let e=YD.default.join(this.workspace.root,".vim");return YD.default.join(e,Gi)}$updateConfigurationOption(e,t,i){this.modifyConfiguration(e,t,i).logError()}$removeConfigurationOption(e,t){this.modifyConfiguration(e,t).logError()}},ej=XD;var Zr=S($i()),ZD=S(require("path")),QD=class{constructor(e){this.filepath=e}fetch(e){let t=this.load();if(!e)return t;let i=e.split(".");for(let n of i){if(typeof t[n]=="undefined")return;t=t[n]}return t}exists(e){let t=this.load(),i=e.split(".");for(let n of i){if(typeof t[n]=="undefined")return!1;t=t[n]}return!0}delete(e){let t=this.load(),i=t,n=e.split("."),o=n.length;for(let s=0;s0){let p=l;for(let d=0;ds.contains(o))||i.push(new _i(o))}return i}contains(e){return e>=this.start&&e<=this.end}},Xf=class{constructor(e){this.ranges=[];e&&(this.ranges=_i.fromKeywordOption(e))}addKeyword(e){let t=e.charCodeAt(0),{ranges:i}=this;i.some(n=>n.contains(t))||i.push(new _i(t))}clone(){let e=new Xf;return e.ranges=this.ranges.slice(),e}setKeywordOption(e){this.ranges=_i.fromKeywordOption(e)}matchKeywords(e,t=3){let i=e.length;if(i==0)return[];let n=new Set,o="",s=0;for(let a=0;a=t&&s<48&&n.add(o),o="",s=0}return s!=0&&n.add(o),Array.from(n)}isKeywordCode(e){return e>255?!0:e<33?!1:this.ranges.some(t=>t.contains(e))}isKeywordChar(e){let{ranges:t}=this,i=e.charCodeAt(0);return i>255?!0:i<33?!1:t.some(n=>n.contains(i))}isKeyword(e){let{ranges:t}=this;for(let i=0,n=e.length;i255)return!1;if(!t.some(s=>s.contains(o)))return!1}return!0}};function Lde(r,e,t=0){let i=e?[t]:[];for(let n=0;ne?n=s:i=s+1}let o=i-1;return{line:o,character:e-t[o]}}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;let i=t[e.line],n=e.line+1{this._fireContentChanges()},100),this.fetchContent=t0.default(()=>{this._fetchContent().logError()},100)}get content(){return this.syncLines.join(` +`)+(this.eol?` +`:"")}get version(){return this._version}get bufnr(){return this.buffer.id}get filetype(){return this._filetype}get uri(){return this._uri}get shouldAttach(){let{buftype:e,maxFileSize:t}=this;return this.getVar("enabled",!0)?this.uri.endsWith("%5BCommand%20Line%5D")?!0:this.size==-2||t&&this.size>t?!1:e==""||e=="acwrite":!1}get isCommandLine(){return this.uri&&this.uri.endsWith("%5BCommand%20Line%5D")}get enabled(){return this.getVar("enabled",!0)}get words(){return this._words}convertFiletype(e){let t=this.env.filetypeMap;return e=="javascript.jsx"?"javascriptreact":e=="typescript.jsx"||e=="typescript.tsx"?"typescriptreact":t[e]||e}get changedtick(){return this._changedtick}get schema(){return $.parse(this.uri).scheme}get lineCount(){return this.lines.length}get winid(){return this._winid}get previewwindow(){return this._previewwindow}async init(e,t){this.nvim=e;let i=await e.call("coc#util#get_bufoptions",[this.bufnr,this.maxFileSize]);if(i==null)return!1;let n=this.buftype=i.buftype;if(this._previewwindow=i.previewwindow,this._winid=i.winid,this.size=typeof i.size=="number"?i.size:0,this.variables=i.variables||{},this._changedtick=i.changedtick,this.eol=i.eol==1,this._uri=uq(i.fullpath,this.bufnr,n,this.env.isCygwin),t.isCancellationRequested)return!1;if(this.shouldAttach){if(this.lines=i.lines,this.syncLines=this.lines,!await this.attach())return!1;this._attached=!0}return this._filetype=this.convertFiletype(i.filetype),this.setIskeyword(i.iskeyword),t.isCancellationRequested?(this.detach(),!1):!0}async attach(){return await this.buffer.attach(!0)?(this.buffer.listen("lines",this.onChange.bind(this),this.disposables),this.buffer.listen("detach",async t=>{this._onDocumentDetach.fire(t.id)},this.disposables),!0):!1}async onChange(e,t,i,n,o){e.id!==this.bufnr||!this._attached||t==null||this.mutex.busy||t>this._changedtick&&(this._changedtick=t,this.lines=[...this.lines.slice(0,i),...o,...this.lines.slice(n)],this.fireContentChanges())}async checkDocument(){let{buffer:e}=this,t=await this.mutex.acquire();this.fireContentChanges.clear(),this._changedtick=await e.changedtick,this.lines=await e.lines,this._fireContentChanges()&&await He(30),t()}get dirty(){return this.lines===this.syncLines?!1:!Ne(this.lines,this.syncLines)}_fireContentChanges(){let{cursor:e}=A,{textDocument:t}=this;try{let i=null;e&&e.bufnr==this.bufnr&&(i=this.getEndOffset(e.lnum,e.col,e.insert));let n=this.getDocumentContent(),o=rj(t.getText(),n,i);if(o==null)return;let s=t.positionAt(o.start),a=t.positionAt(o.end),l=t.getText(Zi.Range.create(s,a));this._version=this._version+1,this.syncLines=this.lines;let u=[{range:{start:s,end:a},rangeLength:o.end-o.start,text:o.newText}];return this._onDocumentChange.fire({bufnr:this.bufnr,original:l,textDocument:{version:this.version,uri:this.uri},contentChanges:u}),this._words=this.chars.matchKeywords(n),!0}catch(i){nj.error(i.message)}return!1}async applyEdits(e){if(!Array.isArray(arguments[0])&&Array.isArray(arguments[1])&&(e=arguments[1]),e.length==0)return;let t=this.getDocumentContent(),i=kt.create(this.uri,this.filetype,1,t),n=kt.applyEdits(i,e);if(Hn&&(n=n.replace(/\r\n/g,` +`)),t!==n){let o=(this.eol&&n.endsWith(` +`)?n.slice(0,-1):n).split(` +`),s=tj(this.lines,o),a=await this.mutex.acquire();try{let l=await this.nvim.call("coc#util#set_lines",[this.bufnr,s.replacement,s.start,s.end]);this._changedtick=l.changedtick,this.lines=o,this.fireContentChanges.clear(),this._fireContentChanges(),Ne(o,l.lines)||process.nextTick(()=>{this.lines=l.lines,this.fireContentChanges.clear(),this._fireContentChanges()}),a()}catch(l){nj.error("Error on applyEdits: ",l),a()}}}async changeLines(e){let t=[],i=this.lines.slice();for(let[o,s]of e)i[o]!=s&&(t.push([o,s]),i[o]=s);if(!t.length)return;let n=await this.mutex.acquire();try{let o=await this.nvim.call("coc#util#change_lines",[this.bufnr,t]);o!=null&&(this.lines=i,this._changedtick=o.changedtick,this.fireContentChanges.clear(),this._fireContentChanges(),Ne(i,o.lines)||process.nextTick(()=>{this.lines=o.lines,this.fireContentChanges.clear(),this._fireContentChanges()})),n()}catch(o){n()}}forceSync(){this.mutex.busy||(this.fireContentChanges.clear(),this._fireContentChanges())}getOffset(e,t){return this.textDocument.offsetAt({line:e-1,character:t})}isWord(e){return this.chars.isKeyword(e)}getMoreWords(){let e=[],{words:t,chars:i}=this;if(!i.isKeywordChar("-"))return e;for(let n of t)if(n=n.replace(/^-+/,""),n.includes("-")){let o=n.split("-");for(let s of o)s.length>2&&!e.includes(s)&&!t.includes(s)&&e.push(s)}return e}getWordRangeAtPosition(e,t,i=!0){let n=this.chars.clone();if(t&&t.length)for(let l of t)n.addKeyword(l);let o=this.getline(e.line,i);if(o.length==0||e.character>=o.length||!n.isKeywordChar(o[e.character]))return null;let s=e.character,a=e.character+1;if(!n.isKeywordChar(o[s]))return Zi.Range.create(e,{line:e.line,character:e.character+1});for(;s>=0;){let l=o[s-1];if(!l||!n.isKeyword(l))break;s=s-1}for(;a<=o.length;){let l=o[a];if(!l||!n.isKeywordChar(l))break;a=a+1}return Zi.Range.create(e.line,s,e.line,a)}get textDocument(){let{version:e,filetype:t,uri:i}=this;return new e0(i,t,e,this.syncLines,this.eol)}async _fetchContent(){if(!this.env.isVim||!this._attached)return;let{nvim:e,bufnr:t,changedtick:i}=this,n=await this.mutex.acquire(),o=await e.call("coc#util#get_buf_lines",[t,i]);o&&o.changedtick>=this._changedtick&&(this._changedtick=o.changedtick,this.lines=o.lines,this.fireContentChanges.clear(),this._fireContentChanges()),n()}async patchChange(e){if(!!this._attached)if(this.env.isVim)if(e){let t=await this.nvim.call("coc#util#get_changeinfo",[]);if(t.changedtick0&&!u&&o==e&&t.push(Zi.Range.create(i.positionAt(s-o.length),i.positionAt(s))),u||(o="")}return t}fixStartcol(e,t){let i=this.getline(e.line);if(!i)return null;let{character:n}=e,o=i.slice(0,n),s=ue(o),{chars:a}=this;for(let l=o.length-1;l>=0;l--){let u=o[l];if(u==" "||!a.isKeywordChar(u)&&!t.includes(u))break;s=s-ue(u)}return s}getline(e,t=!0){return t?this.lines[e]||"":this.syncLines[e]||""}getLines(e,t){return this.lines.slice(e,t)}getDocumentContent(){let e=this.lines.join(` +`);return this.eol?e+` +`:e}getVar(e,t){let i=this.variables[`coc_${e}`];return i===void 0?t:i}getPosition(e,t){let i=this.getline(e-1);if(!i||t==0)return{line:e-1,character:0};let n=Rt(i,0,t-1);return{line:e-1,character:n.length}}getEndOffset(e,t,i){let n=0,o=this.lines.length;for(let s=e-1;s3e4?this.lines.slice(0,3e4):this.lines;this._words=this.chars.matchKeywords(n.join(` +`))}get attached(){return this._attached}detach(){this._attached=!1,z(this.disposables),this.disposables=[],this.fetchContent.clear(),this.fireContentChanges.clear(),this._onDocumentChange.dispose(),this._onDocumentDetach.dispose()}getLocalifyBonus(e,t){let i=new Map,{chars:n}=this,o=Math.max(0,e.line-100),s=Math.min(this.lineCount,e.line+100),a=this.lines.slice(o,s).join(` +`);e=Zi.Position.create(e.line-o,e.character),t=Zi.Position.create(t.line-o,t.character);let l=kt.create(this.uri,this.filetype,1,a),u=l.offsetAt(e),c=a.length,f=c-l.offsetAt(t),p=0,d=!1;for(let h=0;h1){let y=a.slice(p,h);i.set(y,h/u)}d=m}p=c-f,d=!1;for(let h=p;h1){let y=h==c-1?h+1:h,v=a.slice(p,y),x=i.get(v)||0;i.set(v,Math.max(x,(c-h+(y-p))/f))}d=m}return i}},Zm=r0;var Zf=S(W());var sj=S(Qs()),zl=S(require("path"));function Qm(r,e){let t=[[],[]];for(let i of r)e(i)?t[0].push(i):t[1].push(i);return t}function oj(r,e){let t=r.length,i=[];for(let n=0;nr.indexOf(i)===n);let t=Object.create(null);return r.filter(i=>{let n=e(i);return t[n]?!1:(t[n]=!0,!0)})}var aj=j()("filesystem-watcher"),i0=class{constructor(e,t,i,n,o){this.globPattern=t;this.ignoreCreateEvents=i;this.ignoreChangeEvents=n;this.ignoreDeleteEvents=o;this._onDidCreate=new Zf.Emitter;this._onDidChange=new Zf.Emitter;this._onDidDelete=new Zf.Emitter;this._onDidRename=new Zf.Emitter;this.onDidCreate=this._onDidCreate.event;this.onDidChange=this._onDidChange.event;this.onDidDelete=this._onDidDelete.event;this.onDidRename=this._onDidRename.event;this.disposables=[];!e||e.then(s=>{if(s)return this.listen(s)}).catch(s=>{aj.error("watchman initialize failed"),aj.error(s.stack)})}async listen(e){let{globPattern:t,ignoreCreateEvents:i,ignoreChangeEvents:n,ignoreDeleteEvents:o}=this,s=await e.subscribe(t,a=>{let{root:l,files:u}=a;u=u.filter(c=>c.type=="f"&&sj.default(c.name,t,{dot:!0}));for(let c of u){let f=$.file(zl.default.join(l,c.name));c.exists?c.new===!0?i||this._onDidCreate.fire(f):n||this._onDidChange.fire(f):o||this._onDidDelete.fire(f)}if(u.length==2&&!u[0].exists&&u[1].exists){let c=u[0],f=u[1];c.size==f.size&&this._onDidRename.fire({oldUri:$.file(zl.default.join(l,c.name)),newUri:$.file(zl.default.join(l,f.name))})}if(u.length>=2){let[c,f]=Qm(u,p=>p.exists===!1);if(c.length==f.length)for(let p of c){let d=f.find(h=>h.size==p.size&&h.mtime_ms==p.mtime_ms);d&&this._onDidRename.fire({oldUri:$.file(zl.default.join(l,p.name)),newUri:$.file(zl.default.join(l,d.name))})}}});return this.disposables.push(s),s}dispose(){z(this.disposables)}},tg=i0;var n0=S(require("path")),Uo=S($i()),o0=class{constructor(e,t){this.name=e;this.file=n0.default.join(t||process.env.COC_DATA_HOME,e)}async load(){let e=n0.default.dirname(this.file);try{Uo.default.mkdirpSync(e),Uo.default.existsSync(this.file)||Uo.default.writeFileSync(this.file,"","utf8");let t=await Uo.default.readFile(this.file,"utf8");return t=t.trim(),t.length?t.trim().split(` +`):[]}catch(t){return[]}}async add(e){let t=await this.load(),i=t.indexOf(e);i!==-1&&t.splice(i,1),t.unshift(e),Uo.default.writeFileSync(this.file,t.join(` +`),"utf8")}async remove(e){let t=await this.load(),i=t.indexOf(e);i!==-1&&(t.splice(i,1),Uo.default.writeFileSync(this.file,t.join(` +`),"utf8"))}async clean(){try{await Uo.default.unlink(this.file)}catch(e){}}},Gl=o0;var Vl=S(require("path")),lj=S(require("fs"));var Uke=j()("util-decorator");function s0(r,e,t){let i=t.value;if(typeof i!="function")return;let n="$"+e;t.value=function(...o){return this.hasOwnProperty(n)?Promise.resolve(this[n]):new Promise((s,a)=>{Promise.resolve(i.apply(this,o)).then(l=>{this[n]=l,s(l)},l=>{a(l)})})}}var a0=S(iD()),Vke=j()("model-resolver"),Qf=class{get nodeFolder(){return gf("npm")?hn("npm --loglevel silent root -g",{},3e3).then(e=>a0.default(e).trim()):Promise.resolve("")}get yarnFolder(){return gf("yarnpkg")?hn("yarnpkg global dir",{},3e3).then(e=>{let t=Vl.default.join(a0.default(e).trim(),"node_modules");return lj.default.existsSync(t)?t:""}):Promise.resolve("")}async resolveModule(e){let t=await this.nodeFolder,i=await this.yarnFolder;if(i){let n=await Ht(Vl.default.join(i,e,"package.json"));if(n&&n.isFile())return Vl.default.join(i,e)}if(t){let n=await Ht(Vl.default.join(t,e,"package.json"));if(n&&n.isFile())return Vl.default.join(t,e)}return null}};Ty([s0],Qf.prototype,"nodeFolder",1),Ty([s0],Qf.prototype,"yarnFolder",1);var uj=Qf;var rg=S(W());var l0=class{constructor(e,t){this.nvim=e;this.id=t;this.disposables=[];this._onExit=new rg.Emitter;this._onStderr=new rg.Emitter;this._onStdout=new rg.Emitter;this.onExit=this._onExit.event;this.onStdout=this._onStdout.event;this.onStderr=this._onStderr.event;A.on("TaskExit",(o,s)=>{o==this.id&&this._onExit.fire(s)},null,this.disposables),A.on("TaskStderr",(o,s)=>{o==this.id&&this._onStderr.fire(s)},null,this.disposables);let i=[],n;A.on("TaskStdout",(o,s)=>{o==this.id&&(n&&clearTimeout(n),i.push(...s),n=setTimeout(()=>{this._onStdout.fire(i),i=[]},100))},null,this.disposables)}async start(e){let{nvim:t}=this;return await t.call("coc#task#start",[this.id,e])}async stop(){let{nvim:e}=this;await e.call("coc#task#stop",[this.id])}get running(){let{nvim:e}=this;return e.call("coc#task#running",[this.id])}dispose(){let{nvim:e}=this;e.call("coc#task#stop",[this.id],!0),this._onStdout.dispose(),this._onStderr.dispose(),this._onExit.dispose(),z(this.disposables)}},cj=l0;var eIe=j()("model-terminal"),u0=class{constructor(e,t,i,n){this.cmd=e;this.args=t;this.nvim=i;this._name=n;this.pid=0}async start(e,t){let{nvim:i}=this,n=[this.cmd,...this.args],[o,s]=await i.call("coc#terminal#start",[n,e,t||{}]);this.bufnr=o,this.pid=s}get name(){return this._name||this.cmd}get processId(){return Promise.resolve(this.pid)}sendText(e,t=!0){!this.bufnr||this.nvim.call("coc#terminal#send",[this.bufnr,e,t],!0)}async show(e){let{bufnr:t,nvim:i}=this;if(!t)return;let[n,o,s]=await i.eval(`[bufloaded(${t}),bufwinid(${t}),win_getid()]`);return n?(s==o||(i.pauseNotification(),o==-1?(i.command(`below ${t}sb`,!0),i.command("resize 8",!0),i.call("coc#util#do_autocmd",["CocTerminalOpen"],!0)):i.call("win_gotoid",[o],!0),i.command("normal! G",!0),e&&i.command("wincmd p",!0),await i.resumeNotification()),!0):!1}async hide(){let{bufnr:e,nvim:t}=this;if(!e)return;let i=await t.call("bufwinnr",e);i!=-1&&await t.command(`${i}close!`)}dispose(){let{bufnr:e,nvim:t}=this;!e||t.call("coc#terminal#close",[e],!0)}},fj=u0;var c0=class{constructor(e,t){this._create=e;this.workspace=t;this.disposables=[];this.itemsMap=new Map;let{disposables:i}=this;for(let n of t.documents)this.create(n);t.onDidOpenTextDocument(n=>{let o=t.getDocument(n.bufnr);o&&this.create(o)},null,i),t.onDidChangeTextDocument(n=>{this.onChange(n)},null,i),t.onDidCloseTextDocument(n=>{this.delete(n.bufnr)},null,i)}get items(){return Array.from(this.itemsMap.values()).map(e=>e.item)}getItem(e){var i;if(typeof e=="number")return(i=this.itemsMap.get(e))==null?void 0:i.item;let t=Array.from(this.itemsMap.values()).find(n=>n.uri==e);return t?t.item:void 0}create(e){if(!e||e.isCommandLine||!e.attached)return;let t=this.itemsMap.get(e.bufnr);t&&t.item.dispose();let i=this._create(e);i&&this.itemsMap.set(e.bufnr,{uri:e.uri,item:i})}onChange(e){let t=this.itemsMap.get(e.bufnr);t&&typeof t.item.onChange=="function"&&t.item.onChange(e)}delete(e){let t=this.itemsMap.get(e);t&&(this.itemsMap.delete(e),t.item.dispose())}reset(){for(let e of this.itemsMap.values())e.item.dispose();this.itemsMap.clear()}dispose(){z(this.disposables);for(let e of this.itemsMap.values())e.item.dispose();this.itemsMap.clear()}},pj=c0;var dj=S(Qs());function f0(r,e,t){if(Array.isArray(r)){let i=0;for(let n of r){let o=f0(n,e,t);if(o===10)return o;o>i&&(i=o)}return i}else{if(typeof r=="string")return r==="*"?5:r===t?10:0;if(r){let i=$.parse(e),{language:n,pattern:o,scheme:s}=r,a=0;if(s)if(s===i.scheme)a=5;else if(s==="*")a=3;else return 0;if(n)if(n===t)a=10;else if(n==="*")a=Math.max(a,5);else return 0;if(o){let l=Hn||Rx,u=l?o.toLowerCase():o,c=l?i.fsPath.toLowerCase():i.fsPath;if(u===c||dj.default(c,u,{dot:!0}))a=5;else return 0}return a}else return 0}}var Lj=S(Oj()),b0=S(require("os")),ag=S(require("path"));var Mj=S(W()),Nj=S(Qs());var lg=j()("watchman"),Kde=["relative_root","cmd-watch-project","wildmatch","field-new"],w0=new Map,np=class{constructor(e,t){this.channel=t;this._disposed=!1;this.client=new Lj.default.Client({watchmanBinaryPath:e}),this.client.setMaxListeners(300)}checkCapability(){let{client:e}=this;return new Promise((t,i)=>{e.capabilityCheck({optional:[],required:Kde},(n,o)=>{if(n)return i(n);let{capabilities:s}=o;for(let a of Object.keys(s))if(!s[a])return t(!1);t(!0)})})}async watchProject(e){try{let t=await this.command(["watch-project",e]),{watch:i,warning:n,relative_path:o}=t;n&&lg.warn(n),this.watch=i,this.relative_path=o,lg.info(`watchman watching project: ${e}`),this.appendOutput(`watchman watching project: ${e}`)}catch(t){return lg.error(t),!1}return!0}command(e){return new Promise((t,i)=>{this.client.command(e,(n,o)=>{if(n)return i(n);t(o)})})}async subscribe(e,t){let{watch:i,relative_path:n}=this;if(!i)return this.appendOutput(`watchman not watching: ${i}`,"Error"),null;let{clock:o}=await this.command(["clock",i]),s=qo(),a={expression:["allof",["match","**/*","wholename"]],fields:["name","size","new","exists","type","mtime_ms","ctime_ms"],since:o},l=i;n&&(a.relative_root=n,l=ag.default.join(i,n));let{subscribe:u}=await this.command(["subscribe",i,s,a]);return global.hasOwnProperty("__TEST__")&&(global.subscribe=u),this.appendOutput(`subscribing "${e}" in ${l}`),this.client.on("subscription",c=>{if(!c||c.subscription!=s)return;let{files:f}=c;if(!f||(f=f.filter(d=>d.type=="f"&&Nj.default(d.name,e,{dot:!0})),!f.length))return;let p=Object.assign({},c);this.relative_path&&(p.root=ag.default.resolve(c.root,this.relative_path)),this.appendOutput(`file change detected: ${JSON.stringify(p,null,2)}`),t(p)}),Mj.Disposable.create(()=>this.unsubscribe(u))}unsubscribe(e){if(this._disposed)return Promise.resolve();let{watch:t}=this;if(!!t)return this.appendOutput(`unsubscribe "${e}" in: ${t}`),this.command(["unsubscribe",t,e]).catch(i=>{lg.error(i)})}dispose(){this._disposed||(this._disposed=!0,this.client.removeAllListeners(),this.client.end())}appendOutput(e,t="Info"){this.channel&&this.channel.appendLine(`[${t} - ${new Date().toLocaleTimeString()}] ${e}`)}static dispose(){for(let e of w0.values())e.then(t=>{t.dispose()},t=>{})}static createClient(e,t,i){if(!Jde(t))return null;let n=w0.get(t);if(n)return n;let o=new Promise(async(s,a)=>{try{let l=new np(e,i);if(!await l.checkCapability()||!await l.watchProject(t))return s(null);s(l)}catch(l){a(l)}});return w0.set(t,o),o}},ta=np;function Jde(r){return!(r=="/"||r=="/tmp"||r=="/private/tmp"||r.toLowerCase()===b0.default.homedir().toLowerCase()||ag.default.parse(r).base==r||r.startsWith("/tmp/")||r.startsWith("/private/tmp/")||Ye(b0.default.tmpdir(),r,!0))}var ug="0.0.80";var jj=8,op=j()("workspace"),cg=2e3,Yde=["showMessage","runTerminalCommand","openTerminal","showQuickpick","menuPick","openLocalConfig","showPrompt","createStatusBarItem","createOutputChannel","showOutputChannel","requestInput","echoLines","getCursorPosition","moveTo","getOffset"],Uj=class{constructor(){this.keymaps=new Map;this.resolver=new uj;this.rootPatterns=new Map;this._workspaceFolders=[];this._insertMode=!1;this._cwd=process.cwd();this._initialized=!1;this._attached=!1;this.buffers=new Map;this.autocmdMaxId=0;this.autocmds=new Map;this.terminals=new Map;this.creatingSources=new Map;this.schemeProviderMap=new Map;this.namespaceMap=new Map;this.disposables=[];this.watchedOptions=new Set;this._dynAutocmd=!1;this._disposed=!1;this._onDidOpenDocument=new le.Emitter;this._onDidCloseDocument=new le.Emitter;this._onDidChangeDocument=new le.Emitter;this._onWillSaveDocument=new le.Emitter;this._onDidSaveDocument=new le.Emitter;this._onDidChangeWorkspaceFolders=new le.Emitter;this._onDidChangeConfiguration=new le.Emitter;this._onDidWorkspaceInitialized=new le.Emitter;this._onDidOpenTerminal=new le.Emitter;this._onDidCloseTerminal=new le.Emitter;this._onDidRuntimePathChange=new le.Emitter;this.onDidCloseTerminal=this._onDidCloseTerminal.event;this.onDidOpenTerminal=this._onDidOpenTerminal.event;this.onDidChangeWorkspaceFolders=this._onDidChangeWorkspaceFolders.event;this.onDidOpenTextDocument=this._onDidOpenDocument.event;this.onDidCloseTextDocument=this._onDidCloseDocument.event;this.onDidChangeTextDocument=this._onDidChangeDocument.event;this.onWillSaveTextDocument=this._onWillSaveDocument.event;this.onDidSaveTextDocument=this._onDidSaveDocument.event;this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.onDidWorkspaceInitialized=this._onDidWorkspaceInitialized.event;this.onDidRuntimePathChange=this._onDidRuntimePathChange.event;this.version=ug,this.configurations=this.createConfigurations();let e=process.cwd();e!=Qi.default.homedir()&&Bo(e,[".vim"])&&this._workspaceFolders.push({uri:$.file(e).toString(),name:ke.default.basename(e)})}async init(){let{nvim:e}=this;for(let o of Yde)Object.defineProperty(this,o,{get:()=>(...s)=>C[o].apply(C,s)});this._env=await e.call("coc#util#vim_info"),this._env.apiversion!=jj&&(console.error(`API version ${this._env.apiversion} is not ${jj}, please build coc.nvim by 'yarn install' after pull source code.`),process.exit()),this._insertMode=this._env.mode.startsWith("insert");let i=this.getConfiguration("coc.preferences").get("maxFileSize","10MB");this.maxFileSize=qj.default.parse(i),this._env.workspaceFolders&&(this._workspaceFolders=this._env.workspaceFolders.map(o=>({uri:$.file(o).toString(),name:ke.default.dirname(o)}))),this.configurations.updateUserConfig(this._env.config),A.on(["InsertEnter","CursorMovedI"],()=>{this._insertMode=!0},null,this.disposables),A.on(["InsertLeave","CursorMoved"],()=>{this._insertMode=!1},null,this.disposables);let n=async o=>{let s=this.getDocument(o);s&&s.forceSync()};A.on("InsertLeave",n,null,this.disposables),A.on("CursorHold",n,null,this.disposables),A.on("BufEnter",this.onBufEnter,this,this.disposables),A.on("CursorMoved",this.checkCurrentBuffer,this,this.disposables),A.on("CursorMovedI",this.checkCurrentBuffer,this,this.disposables),A.on("DirChanged",this.onDirChanged,this,this.disposables),A.on("BufCreate",this.onBufCreate,this,this.disposables),A.on("BufUnload",this.onBufUnload,this,this.disposables),A.on("TermOpen",this.onBufCreate,this,this.disposables),A.on("TermClose",this.onBufUnload,this,this.disposables),A.on("BufWritePost",this.onBufWritePost,this,this.disposables),A.on("BufWritePre",this.onBufWritePre,this,this.disposables),A.on("FileType",this.onFileTypeChange,this,this.disposables),A.on("CursorHold",this.checkCurrentBuffer,this,this.disposables),A.on("TextChanged",this.checkBuffer,this,this.disposables),A.on("BufReadCmd",this.onBufReadCmd,this,this.disposables),A.on("VimResized",(o,s)=>{Object.assign(this._env,{columns:o,lines:s})},null,this.disposables),await this.attach(),this.attachChangedEvents(),this.configurations.onDidChange(o=>{this._onDidChangeConfiguration.fire(o)},null,this.disposables),this.watchOption("runtimepath",(o,s)=>{let a=$j.default(o,s);for(let[l,u]of a)if(l==1){let c=u.replace(/,$/,"").split(",");this._onDidRuntimePathChange.fire(c)}this._env.runtimepath=s},this.disposables),this.watchOption("completeopt",async(o,s)=>{if(this.env.completeOpt=s,!!this._attached&&this.insertMode&&this.getConfiguration("suggest").get("autoTrigger")=="always"){let u=(await this.nvim.call("execute",["verbose set completeopt"])).split(/\r?\n/);console.error(`Some plugin change completeopt on insert mode: ${u[u.length-1].trim()}!`)}},this.disposables),this.watchGlobal("coc_sources_disable_map",async(o,s)=>{this.env.disabledSources=s}),this.disposables.push(this.registerTextDocumentContentProvider("output",Xs.getProvider(e)))}getConfigFile(e){return this.configurations.getConfigFile(e)}registerAutocmd(e){this.autocmdMaxId+=1;let t=this.autocmdMaxId;return this.autocmds.set(t,e),this.setupDynamicAutocmd(),le.Disposable.create(()=>{this.autocmds.delete(t),this.setupDynamicAutocmd()})}watchOption(e,t,i){let n=this.watchedOptions.has(e);n||(this.watchedOptions.add(e),this.setupDynamicAutocmd());let o=A.on("OptionSet",async(s,a,l)=>{s==e&&t&&await Promise.resolve(t(a,l))});i&&i.push(le.Disposable.create(()=>{o.dispose(),!n&&(this.watchedOptions.delete(e),this.setupDynamicAutocmd())}))}watchGlobal(e,t,i){let{nvim:n}=this;n.call("coc#_watch",e,!0);let o=A.on("GlobalChange",async(s,a,l)=>{s==e&&t&&await Promise.resolve(t(a,l))});i&&i.push(le.Disposable.create(()=>{o.dispose(),n.call("coc#_unwatch",e,!0)}))}get cwd(){return this._cwd}get env(){return this._env}get root(){return this._root||this.cwd}get rootPath(){return this.root}get workspaceFolders(){return this._workspaceFolders}get uri(){let{bufnr:e}=this;if(e){let t=this.getDocument(e);if(t&&t.schema=="file")return t.uri}return null}get workspaceFolder(){let{rootPath:e}=this;return e==Qi.default.homedir()?null:{uri:$.file(e).toString(),name:ke.default.basename(e)}}get textDocuments(){let e=[];for(let t of this.buffers.values())e.push(t.textDocument);return e}get documents(){return Array.from(this.buffers.values())}createNameSpace(e=""){return this.namespaceMap.has(e)?this.namespaceMap.get(e):(cg=cg+1,this.namespaceMap.set(e,cg),cg)}get channelNames(){return Xs.names}get pluginRoot(){return ke.default.dirname(__dirname)}get isVim(){return this._env.isVim}get isNvim(){return!this._env.isVim}get completeOpt(){return this._env.completeOpt}get initialized(){return this._initialized}get ready(){return this._initialized?Promise.resolve():new Promise(e=>{let t=this.onDidWorkspaceInitialized(()=>{t.dispose(),e()})})}get filetypes(){let e=new Set;for(let t of this.documents)e.add(t.filetype);return e}match(e,t){return f0(e,t.uri,t.languageId)}async findUp(e){let{cwd:t}=this,i=await this.nvim.call("expand","%:p");i=ke.default.normalize(i);let n=i&&ke.default.isAbsolute(i);if(n&&!Ye(t,i,!0))return Hl(e,ke.default.dirname(i));let o=Hl(e,t);return o&&o!=Qi.default.homedir()?o:n?Hl(e,ke.default.dirname(i)):null}async resolveRootFolder(e,t){let{cwd:i}=this;if(e.scheme!="file")return i;let n=ke.default.normalize(e.fsPath),o=ke.default.dirname(n);return Jf(o,t)||o}createFileSystemWatcher(e,t,i,n){let o=global.hasOwnProperty("__TEST__")?null:this.getWatchmanPath(),s=o?C.createOutputChannel("watchman"):null,a=o?ta.createClient(o,this.root,s):Promise.resolve(null);return new tg(a,e,!!t,!!i,!!n)}getWatchmanPath(){let t=this.getConfiguration("coc.preferences").get("watchmanPath","watchman");try{return Bj.default.sync(t)}catch(i){return null}}getConfiguration(e,t){return this.configurations.getConfiguration(e,t)}getDocument(e){if(typeof e=="number")return this.buffers.get(e);let t=Cl.isWindows||Cl.isMacintosh;e=$.parse(e).toString();for(let i of this.buffers.values())if(!!i&&(i.uri===e||t&&i.uri.toLowerCase()===e.toLowerCase()))return i;return null}async applyEdit(e){let{nvim:t}=this,{documentChanges:i,changes:n}=e,[o,s]=await t.eval('[bufnr("%"),coc#util#cursor()]'),a=this.getDocument(o),l=a?a.uri:null,u=null,c=[],f=0,p=this.getConfiguration("coc.preferences"),d=!global.hasOwnProperty("__TEST__")&&p.get("promptWorkspaceEdit",!0),h=p.get("listOfWorkspaceEdit","quickfix");try{if(i&&i.length){let m=this.getChangedUris(i);if(f=m.length,d){let x=m.reduce((w,E)=>w+(this.getDocument(E)==null?1:0),0);if(x&&!await C.showPrompt(`${x} documents on disk would be loaded for change, confirm?`))return}let y=new Map,v=[];for(let x=0;x{let w=y.get(x.uri);w&&(x.uri=w)})}else if(n){let m=Object.keys(n),y=m.filter(v=>this.getDocument(v)==null);if(y.length){if(d&&!await C.showPrompt(`${y.length} documents on disk would be loaded for change, confirm?`))return;await this.loadFiles(y)}for(let v of Object.keys(n)){let x=this.getDocument(v);$.parse(v).toString()==v&&(u=n[v]);let w=n[v];for(let E of w)c.push({uri:x.uri,range:E.range});await x.applyEdits(w)}f=m.length}if(u){let m=$l({line:s[0],character:s[1]},u);m&&await C.moveTo({line:s[0]+m.line,character:s[1]+m.character})}if(c.length){let m=await Promise.all(c.map(v=>this.getQuickfixItem(v))),y=c.every(v=>v.uri==l);h=="quickfix"?(await this.nvim.call("setqflist",[m]),y||C.showMessage(`changed ${f} buffers, use :wa to save changes to disk and :copen to open quickfix list`,"more")):h=="location"&&(await t.setVar("coc_jump_locations",m),y||C.showMessage(`changed ${f} buffers, use :wa to save changes to disk and :CocList location to manage changed locations`,"more"))}}catch(m){return op.error(m),C.showMessage(`Error on applyEdits: ${m.message}`,"error"),!1}return await He(50),!0}async getQuickfixItem(e,t,i="",n){le.LocationLink.is(e)&&(e=le.Location.create(e.targetUri,e.targetRange));let o=this.getDocument(e.uri),{uri:s,range:a}=e,{line:l,character:u}=a.start,c=$.parse(s),f=o?o.bufnr:-1;!t&&c.scheme=="file"&&(t=await this.getLine(s,l),u=Vr(t,u));let p={uri:s,filename:c.scheme=="file"?c.fsPath:s,lnum:l+1,col:u+1,text:t||"",range:a};return n&&(p.module=n),i&&(p.type=i),f!=-1&&(p.bufnr=f),p}createMru(e){return new Gl(e)}async getSelectedRange(e,t){let{nvim:i}=this;if(e==="line"){let c=await i.call("line",["."]),f=t.getline(c-1);return f.length?le.Range.create(c-1,0,c-1,f.length):null}if(e==="cursor"){let[c,f]=await i.eval("coc#util#cursor()");return le.Range.create(c,f,c,f)}if(!["v","V","char","line",""].includes(e))throw new Error(`Mode '${e}' not supported`);let n=["v","V",""].includes(e),[,o,s]=await i.call("getpos",n?"'<":"'["),[,a,l]=await i.call("getpos",n?"'>":"']"),u=le.Range.create(t.getPosition(o,s),t.getPosition(a,l));return(e=="v"||e=="")&&(u.end.character=u.end.character+1),u}async selectRange(e){let{nvim:t}=this,{start:i,end:n}=e,[o,s,a]=await t.eval("[bufnr('%'), &virtualedit, &selection, mode()]"),l=this.getDocument(o);if(!l)return;let u=l.getline(i.line),c=u?ue(u.slice(0,i.character)):0,f=l.getline(n.line),p=f?ue(f.slice(0,n.character)):0,d="",h=!1;d+="v",p=await t.eval(`virtcol([${n.line+1}, ${p}])`),a=="inclusive"?n.character==0?d+=`${n.line}G`:d+=`${n.line+1}G${p}|`:a=="old"?d+=`${n.line+1}G${p}|`:d+=`${n.line+1}G${p+1}|`,c=await t.eval(`virtcol([${i.line+1}, ${c}])`),d+=`o${i.line+1}G${c+1}|o`,t.pauseNotification(),s!="onemore"&&(h=!0,t.setOption("virtualedit","onemore",!0)),t.command(`noa call cursor(${i.line+1},${c+(d=="a"?0:1)})`,!0),t.command(`normal! ${d}`,!0),h&&t.setOption("virtualedit",s,!0),this.isVim&&t.command("redraw",!0),await t.resumeNotification()}async showLocations(e){let t=await Promise.all(e.map(o=>this.getQuickfixItem(o))),{nvim:i}=this;if(this.getConfiguration("coc.preferences").get("useQuickfixForLocations",!1)){let o=await i.getVar("coc_quickfix_open_command");typeof o!="string"&&(o=t.length<10?`copen ${t.length}`:"copen"),i.pauseNotification(),i.call("setqflist",[t],!0),i.command(o,!0),i.resumeNotification(!1,!0)}else await i.setVar("coc_jump_locations",t),this.env.locationlist?i.command("CocList --normal --auto-preview location",!0):i.call("coc#util#do_autocmd",["CocLocationsChange"],!0)}async getLine(e,t){let i=this.getDocument(e);if(i)return i.getline(t)||"";if(!e.startsWith("file:"))return"";let n=$.parse(e).fsPath;return Dt.default.existsSync(n)?await X3(n,t):""}getWorkspaceFolder(e){this.workspaceFolders.sort((i,n)=>n.uri.length-i.uri.length);let t=$.parse(e).fsPath;return this.workspaceFolders.find(i=>Ye($.parse(i.uri).fsPath,t,!0))}async readFile(e){let t=this.getDocument(e);if(t)return await t.patchChange(),t.content;let i=$.parse(e);return i.scheme!="file"?"":(await this.nvim.call("readfile",[i.fsPath])).join(` +`)+` +`}get document(){return new Promise((e,t)=>{this.nvim.buffer.then(i=>{let n=i.id;if(this.bufnr=n,this.buffers.has(n)){e(this.buffers.get(n));return}this.onBufCreate(n).catch(t);let o=this.onDidOpenTextDocument(s=>{o.dispose(),e(this.getDocument(s.uri))})},t)})}async getCurrentState(){let e=await this.document,t=await C.getCursorPosition();return{document:e.textDocument,position:t}}async getFormatOptions(e){let t;e&&(t=this.getDocument(e));let i=t?t.bufnr:0,[n,o]=await this.nvim.call("coc#util#get_format_opts",[i]);return{tabSize:n,insertSpaces:o==1}}async jumpTo(e,t,i){let n=this.getConfiguration("coc.preferences"),o=i||n.get("jumpCommand","edit"),{nvim:s}=this,a=this.getDocument(e),l=a?a.bufnr:-1;if(l!=-1&&o=="edit"){if(s.pauseNotification(),s.command("silent! normal! m'",!0),s.command(`buffer ${l}`,!0),t){let u=a.getline(t.line),c=ue(u.slice(0,t.character))+1;s.call("cursor",[t.line+1,c],!0)}this.isVim&&s.command("redraw",!0),await s.resumeNotification()}else{let{fsPath:u,scheme:c}=$.parse(e),f=t==null?null:[t.line,t.character];if(c=="file"){let p=Kf(ke.default.normalize(u));await this.nvim.call("coc#util#jump",[o,p,f])}else Qi.default.platform()=="win32"&&(e=e.replace(/\/?/,"?")),await this.nvim.call("coc#util#jump",[o,e,f])}}async createFile(e,t={}){let i=await Ht(e);if(i&&!t.overwrite&&!t.ignoreIfExists){C.showMessage(`${e} already exists!`,"error");return}if(!i||t.overwrite)if(e.endsWith("/"))try{e=this.expand(e),await Dt.default.mkdirp(e)}catch(n){C.showMessage(`Can't create ${e}: ${n.message}`,"error")}else{let n=$.file(e).toString();if(this.getDocument(n))return;Dt.default.existsSync(ke.default.dirname(e))||Dt.default.mkdirpSync(ke.default.dirname(e)),Dt.default.writeFileSync(e,"","utf8"),await this.loadFile(n)}}async loadFile(e){let t=this.getDocument(e);if(t)return t;let{nvim:i}=this,n=e.startsWith("file")?$.parse(e).fsPath:e;return i.call("coc#util#open_files",[[n]],!0),await new Promise((o,s)=>{let a=this.onDidOpenTextDocument(u=>{let c=$.parse(u.uri).fsPath;(u.uri==e||c==n)&&(clearTimeout(l),a.dispose(),o(this.getDocument(e)))}),l=setTimeout(()=>{a.dispose(),s(new Error(`Create document ${e} timeout after 1s.`))},1e3)})}async loadFiles(e){if(e=e.filter(n=>this.getDocument(n)==null),!(!e.length||!(await this.nvim.call("coc#util#open_files",[e.map(n=>$.parse(n).fsPath)])).filter(n=>this.getDocument(n)==null).length))return new Promise((n,o)=>{let s=setTimeout(()=>{a.dispose(),o(new Error("Create document timeout after 2s."))},2e3),a=this.onDidOpenTextDocument(()=>{e.every(l=>this.getDocument(l)!=null)&&(clearTimeout(s),a.dispose(),n())})})}async renameFile(e,t,i={}){let{overwrite:n,ignoreIfExists:o}=i,{nvim:s}=this;try{let a=await Ht(t);if(a&&!n&&!o)throw new Error(`${t} already exists`);if(!a||n){let l=$.file(e).toString(),u=$.file(t).toString(),c=this.getDocument(l);if(c!=null){let f=c.bufnr==this.bufnr,p=this.getDocument(u);p&&await this.nvim.command(`silent ${p.bufnr}bwipeout!`);let d=c.getDocumentContent();if(await Dt.default.writeFile(t,d,"utf8"),!f)await s.call("coc#util#open_files",[[t]]),await s.command(`silent ${c.bufnr}bwipeout!`);else{let h=await s.call("winsaveview");s.pauseNotification(),s.call("coc#util#open_file",["keepalt edit",t],!0),s.command(`silent ${c.bufnr}bwipeout!`,!0),s.call("winrestview",[h],!0),await s.resumeNotification()}await Dt.default.unlink(e)}else await K3(e,t)}}catch(a){C.showMessage(`Rename error: ${a.message}`,"error")}}async deleteFile(e,t={}){let{ignoreIfNotExists:i,recursive:n}=t,o=await Ht(e.replace(/\/$/,"")),s=o&&o.isDirectory();if(e.endsWith("/")&&!s){C.showMessage(`${e} is not directory`,"error");return}if(!o&&!i){C.showMessage(`${e} not exists`,"error");return}if(o!=null){if(s&&!n){C.showMessage("Can't remove directory, recursive not set","error");return}try{if(s&&n?await Dt.default.remove(e):s?await Dt.default.rmdir(e):await Dt.default.unlink(e),!s){let a=$.file(e).toString(),l=this.getDocument(a);l&&await this.nvim.command(`silent! bwipeout! ${l.bufnr}`)}}catch(a){C.showMessage(`Error on delete ${e}: ${a.message}`,"error")}}}async openResource(e){let{nvim:t}=this;if(e.startsWith("http")){await t.call("coc#util#open_url",e);return}let i=await t.getOption("wildignore");await t.setOption("wildignore",""),await this.jumpTo(e),await t.setOption("wildignore",i)}async resolveModule(e){return await this.resolver.resolveModule(e)}async runCommand(e,t,i){return t=t||this.cwd,hn(e,{cwd:t},i)}expand(e){if(!e)return e;if(e.startsWith("~")&&(e=Qi.default.homedir()+e.slice(1)),e.includes("$")){let t=this.getDocument(this.bufnr),i=t?$.parse(t.uri).fsPath:"";e=e.replace(/\$\{(.*?)\}/g,(n,o)=>{if(o.startsWith("env:")){let s=o.split(":")[1];return s?process.env[s]:""}switch(o){case"workspace":case"workspaceRoot":case"workspaceFolder":return this.root;case"workspaceFolderBasename":return ke.default.dirname(this.root);case"cwd":return this.cwd;case"file":return i;case"fileDirname":return i?ke.default.dirname(i):"";case"fileExtname":return i?ke.default.extname(i):"";case"fileBasename":return i?ke.default.basename(i):"";case"fileBasenameNoExtension":{let s=i?ke.default.basename(i):"";return s?s.slice(0,s.length-ke.default.extname(s).length):""}default:return n}}),e=e.replace(/\$[\w]+/g,n=>n=="$HOME"?Qi.default.homedir():process.env[n.slice(1)]||n)}return e}async createTerminal(e){let t=e.shellPath,i=e.shellArgs;t||(t=await this.nvim.getOption("shell"));let n=new fj(t,i||[],this.nvim,e.name);return await n.start(e.cwd||this.cwd,e.env),this.terminals.set(n.bufnr,n),this._onDidOpenTerminal.fire(n),n}async callAsync(e,t){return this.isNvim?await this.nvim.call(e,t):await this.nvim.callAsync("coc#util#with_callback",[e,t])}registerTextDocumentContentProvider(e,t){this.schemeProviderMap.set(e,t),this.setupDynamicAutocmd();let i=[];return t.onDidChange&&t.onDidChange(async n=>{let o=this.getDocument(n.toString());if(o){let{buffer:s}=o,a=new le.CancellationTokenSource,l=await Promise.resolve(t.provideTextDocumentContent(n,a.token));await s.setLines(l.split(/\r?\n/),{start:0,end:-1,strictIndexing:!1})}},null,i),le.Disposable.create(()=>{this.schemeProviderMap.delete(e),z(i),this.setupDynamicAutocmd()})}registerKeymap(e,t,i,n={}){if(!t)throw new Error(`Invalid key ${t} of registerKeymap`);if(this.keymaps.has(t))throw new Error(`${t} already exists.`);n=Object.assign({sync:!0,cancel:!0,silent:!0,repeat:!1},n);let{nvim:o}=this;this.keymaps.set(t,[i,!!n.repeat]);let s=n.sync?"request":"notify",a=n.silent?"":"";for(let l of e)if(l=="i")o.command(`inoremap ${a} (coc-${t}) coc#_insert_key('${s}', '${t}', ${n.cancel?1:0})`,!0);else{let u=Fx(l);o.command(`${l}noremap ${a} (coc-${t}) :${u}call coc#rpc#${s}('doKeymap', ['${t}'])`,!0)}return le.Disposable.create(()=>{this.keymaps.delete(t);for(let l of e)o.command(`${l}unmap (coc-${t})`,!0)})}registerExprKeymap(e,t,i,n=!1){if(!t)return;let o=`${e}${global.Buffer.from(t).toString("base64")}${n?"1":"0"}`,{nvim:s}=this;return this.keymaps.set(o,[i,!1]),e=="i"?s.command(`inoremap ${n?"":""} ${t} coc#_insert_key('request', '${o}')`,!0):s.command(`${e}noremap ${n?"":""} ${t} coc#rpc#request('doKeymap', ['${o}'])`,!0),le.Disposable.create(()=>{this.keymaps.delete(o),s.command(`${e}unmap ${n?"":""} ${t}`,!0)})}registerLocalKeymap(e,t,i,n=!1){let o=qo(),{nvim:s}=this;this.keymaps.set(o,[i,!1]);let a=this.nvim.createBuffer(this.bufnr),l=n?"notify":"request",u=Fx(e),c=t.startsWith("<")&&t.endsWith(">")?`{${t.slice(1,-1)}}`:t;if(this.isNvim&&!global.hasOwnProperty("__TEST__"))a.notify("nvim_buf_set_keymap",[e,t,`:${u}call coc#rpc#${l}('doKeymap', ['${o}', '', '${c}'])`,{silent:!0,nowait:!0}]);else{let f=`${e}noremap ${t} :${u}call coc#rpc#${l}('doKeymap', ['${o}', '', '${c}'])`;s.command(f,!0)}return le.Disposable.create(()=>{this.keymaps.delete(o),s.call("coc#compat#buf_del_keymap",[a.id,e,t],!0)})}createDatabase(e){let t;global.hasOwnProperty("__TEST__")?(t=ke.default.join(Qi.default.tmpdir(),`coc-${process.pid}`),Dt.default.mkdirpSync(t)):t=ke.default.dirname(this.env.extensionRoot);let i=ke.default.join(t,e+".json");return new Ym(i)}createTask(e){return new cj(this.nvim,e)}registerBufferSync(e){return new pj(e,this)}setupDynamicAutocmd(e=!1){if(!e&&!this._dynAutocmd)return;this._dynAutocmd=!0;let t=this.schemeProviderMap.keys(),i=[];for(let o of t)i.push(`autocmd BufReadCmd,FileReadCmd,SourceCmd ${o}:/* call coc#rpc#request('CocAutocmd', ['BufReadCmd','${o}', expand('')])`);for(let[o,s]of this.autocmds.entries()){let a=s.arglist&&s.arglist.length?", "+s.arglist.join(", "):"",l=Array.isArray(s.event)?s.event.join(","):s.event,u=s.pattern!=null?s.pattern:"*";/\buser\b/i.test(l)&&(u=""),i.push(`autocmd ${l} ${u} call coc#rpc#${s.request?"request":"notify"}('doAutocmd', [${o}${a}])`)}for(let o of this.watchedOptions)i.push(`autocmd OptionSet ${o} call coc#rpc#notify('OptionSet',[expand(''), v:option_old, v:option_new])`);let n=` augroup coc_dynamic_autocmd autocmd! - ${cmds.join('\n ')} -augroup end`; - try { - let dir = path_1.default.join(process.env.TMPDIR, `coc.nvim-${process.pid}`); - if (!fs_1.default.existsSync(dir)) - fs_1.default.mkdirSync(dir, { recursive: true }); - let filepath = path_1.default.join(dir, `coc-${process.pid}.vim`); - fs_1.default.writeFileSync(filepath, content, 'utf8'); - let cmd = `source ${filepath}`; - if (this.env.isCygwin && index_1.platform.isWindows) { - cmd = `execute "source" . substitute(system('cygpath ${filepath.replace(/\\/g, '/')}'), '\\n', '', 'g')`; - } - this.nvim.command(cmd).logError(); - } - catch (e) { - this.showMessage(`Can't create tmp file: ${e.message}`, 'error'); - } - } - async onBufReadCmd(scheme, uri) { - let provider = this.schemeProviderMap.get(scheme); - if (!provider) { - this.showMessage(`Provider for ${scheme} not found`, 'error'); - return; - } - let tokenSource = new vscode_languageserver_protocol_1.CancellationTokenSource(); - let content = await Promise.resolve(provider.provideTextDocumentContent(vscode_uri_1.URI.parse(uri), tokenSource.token)); - let buf = await this.nvim.buffer; - await buf.setLines(content.split('\n'), { - start: 0, - end: -1, - strictIndexing: false - }); - setTimeout(async () => { - await events_1.default.fire('BufCreate', [buf.id]); - }, 30); - } - async attach() { - if (this._attached) - return; - this._attached = true; - let buffers = await this.nvim.buffers; - let bufnr = this.bufnr = await this.nvim.call('bufnr', '%'); - await Promise.all(buffers.map(buf => this.onBufCreate(buf))); - if (!this._initialized) { - this._onDidWorkspaceInitialized.fire(void 0); - this._initialized = true; - } - await events_1.default.fire('BufEnter', [bufnr]); - let winid = await this.nvim.call('win_getid'); - await events_1.default.fire('BufWinEnter', [bufnr, winid]); - } - // count of document need change - getChangedUris(documentChanges) { - let uris = new Set(); - let newUris = new Set(); - for (let change of documentChanges) { - if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change)) { - let { textDocument } = change; - let { uri, version } = textDocument; - if (!newUris.has(uri)) { - uris.add(uri); - } - if (version != null && version > 0) { - let doc = this.getDocument(uri); - if (!doc) { - throw new Error(`${uri} not loaded`); - } - if (doc.version != version) { - throw new Error(`${uri} changed before apply edit`); - } - } - else if (fs_2.isFile(uri) && !this.getDocument(uri)) { - let file = vscode_uri_1.URI.parse(uri).fsPath; - if (!fs_1.default.existsSync(file)) { - throw new Error(`file "${file}" not exists`); - } - } - } - else if (vscode_languageserver_protocol_1.CreateFile.is(change) || vscode_languageserver_protocol_1.DeleteFile.is(change)) { - if (!fs_2.isFile(change.uri)) { - throw new Error(`change of scheme ${change.uri} not supported`); - } - uris.add(change.uri); - } - else if (vscode_languageserver_protocol_1.RenameFile.is(change)) { - if (!fs_2.isFile(change.oldUri) || !fs_2.isFile(change.newUri)) { - throw new Error(`change of scheme ${change.oldUri} not supported`); - } - let newFile = vscode_uri_1.URI.parse(change.newUri).fsPath; - if (fs_1.default.existsSync(newFile)) { - throw new Error(`file "${newFile}" already exists for rename`); - } - uris.add(change.oldUri); - newUris.add(change.newUri); - } - else { - throw new Error(`Invalid document change: ${JSON.stringify(change, null, 2)}`); - } - } - return Array.from(uris); - } - createConfigurations() { - let home = path_1.default.normalize(process.env.COC_VIMCONFIG) || path_1.default.join(os_1.default.homedir(), '.vim'); - let userConfigFile = path_1.default.join(home, index_1.CONFIG_FILE_NAME); - return new configuration_1.default(userConfigFile, new shape_1.default(this)); - } - // events for sync buffer of vim - attachChangedEvents() { - if (this.isVim) { - const onChange = (bufnr) => { - let doc = this.getDocument(bufnr); - if (doc && doc.attached) - doc.fetchContent(); - }; - events_1.default.on('TextChangedI', onChange, null, this.disposables); - events_1.default.on('TextChanged', onChange, null, this.disposables); - } - } - async onBufCreate(buf) { - let buffer = typeof buf === 'number' ? this.nvim.createBuffer(buf) : buf; - let bufnr = buffer.id; - if (this.creatingSources.has(bufnr)) - return; - let document = this.getDocument(bufnr); - let source = new vscode_languageserver_protocol_1.CancellationTokenSource(); - try { - if (document) - this.onBufUnload(bufnr, true); - document = new document_1.default(buffer, this._env, this.maxFileSize); - let token = source.token; - this.creatingSources.set(bufnr, source); - let created = await document.init(this.nvim, token); - if (!created) - document = null; - } - catch (e) { - logger.error('Error on create buffer:', e); - document = null; - } - if (this.creatingSources.get(bufnr) == source) { - source.dispose(); - this.creatingSources.delete(bufnr); - } - if (!document || !document.textDocument) - return; - this.buffers.set(bufnr, document); - if (document.attached) { - document.onDocumentDetach(bufnr => { - let doc = this.getDocument(bufnr); - if (doc) - this.onBufUnload(doc.bufnr); - }); - } - if (document.buftype == '' && document.schema == 'file') { - let config = this.getConfiguration('workspace'); - let filetypes = config.get('ignoredFiletypes', []); - if (!filetypes.includes(document.filetype)) { - let root = this.resolveRoot(document); - if (root) { - this.addWorkspaceFolder(root); - if (this.bufnr == buffer.id) { - this._root = root; - } - } - } - this.configurations.checkFolderConfiguration(document.uri); - } - if (document.enabled) { - let textDocument = Object.assign(document.textDocument, { bufnr }); - this._onDidOpenDocument.fire(textDocument); - document.onDocumentChange(e => this._onDidChangeDocument.fire(e)); - } - logger.debug('buffer created', buffer.id); - } - onBufEnter(bufnr) { - this.bufnr = bufnr; - let doc = this.getDocument(bufnr); - if (doc) { - this.configurations.setFolderConfiguration(doc.uri); - let workspaceFolder = this.getWorkspaceFolder(doc.uri); - if (workspaceFolder) - this._root = vscode_uri_1.URI.parse(workspaceFolder.uri).fsPath; - } - } - async checkCurrentBuffer(bufnr) { - this.bufnr = bufnr; - await this.checkBuffer(bufnr); - } - onBufWritePost(bufnr) { - let doc = this.buffers.get(bufnr); - if (!doc) - return; - this._onDidSaveDocument.fire(doc.textDocument); - } - onBufUnload(bufnr, recreate = false) { - logger.debug('buffer unload', bufnr); - if (!recreate) { - let source = this.creatingSources.get(bufnr); - if (source) { - source.cancel(); - this.creatingSources.delete(bufnr); - } - } - if (this.terminals.has(bufnr)) { - let terminal = this.terminals.get(bufnr); - this._onDidCloseTerminal.fire(terminal); - this.terminals.delete(bufnr); - } - let doc = this.buffers.get(bufnr); - if (doc) { - let textDocument = Object.assign(doc.textDocument, { bufnr }); - this._onDidCloseDocument.fire(textDocument); - this.buffers.delete(bufnr); - doc.detach(); - } - } - async onBufWritePre(bufnr) { - let doc = this.buffers.get(bufnr); - if (!doc) - return; - let event = { - document: doc.textDocument, - reason: vscode_languageserver_protocol_1.TextDocumentSaveReason.Manual - }; - this._onWillSaveDocument.fire(event); - if (this.willSaveUntilHandler.hasCallback) { - await this.willSaveUntilHandler.handeWillSaveUntil(event); - } - } - onDirChanged(cwd) { - if (cwd == this._cwd) - return; - this._cwd = cwd; - } - onFileTypeChange(filetype, bufnr) { - let doc = this.getDocument(bufnr); - if (!doc) - return; - let converted = doc.convertFiletype(filetype); - if (converted == doc.filetype) - return; - let textDocument = Object.assign(doc.textDocument, { bufnr }); - this._onDidCloseDocument.fire(textDocument); - doc.setFiletype(filetype); - this._onDidOpenDocument.fire(textDocument); - } - async checkBuffer(bufnr) { - if (this._disposed || !bufnr) - return; - let doc = this.getDocument(bufnr); - if (!doc && !this.creatingSources.has(bufnr)) - await this.onBufCreate(bufnr); - } - async getFileEncoding() { - let encoding = await this.nvim.getOption('fileencoding'); - return encoding ? encoding : 'utf-8'; - } - resolveRoot(document) { - let types = [types_1.PatternType.Buffer, types_1.PatternType.LanguageServer, types_1.PatternType.Global]; - let u = vscode_uri_1.URI.parse(document.uri); - let dir = path_1.default.dirname(u.fsPath); - let { cwd } = this; - for (let patternType of types) { - let patterns = this.getRootPatterns(document, patternType); - if (patterns && patterns.length) { - let root = fs_2.resolveRoot(dir, patterns, cwd); - if (root) - return root; - } - } - if (this.cwd != os_1.default.homedir() && fs_2.isParentFolder(this.cwd, dir, true)) - return this.cwd; - return null; - } - getRootPatterns(document, patternType) { - let { uri } = document; - if (patternType == types_1.PatternType.Buffer) - return document.getVar('root_patterns', []) || []; - if (patternType == types_1.PatternType.LanguageServer) - return this.getServerRootPatterns(document.filetype); - const preferences = this.getConfiguration('coc.preferences', uri); - return preferences.get('rootPatterns', ['.git', '.hg', '.projections.json']).slice(); - } - async renameCurrent() { - let { nvim } = this; - let bufnr = await nvim.call('bufnr', '%'); - let cwd = await nvim.call('getcwd'); - let doc = this.getDocument(bufnr); - if (!doc || doc.buftype != '' || doc.schema != 'file') { - nvim.errWriteLine('current buffer is not file.'); - return; - } - let oldPath = vscode_uri_1.URI.parse(doc.uri).fsPath; - // await nvim.callAsync() - let newPath = await nvim.callAsync('coc#util#with_callback', ['input', ['New path: ', oldPath, 'file']]); - newPath = newPath ? newPath.trim() : null; - if (newPath == oldPath || !newPath) - return; - let lines = await doc.buffer.lines; - let exists = fs_1.default.existsSync(oldPath); - if (exists) { - let modified = await nvim.eval('&modified'); - if (modified) - await nvim.command('noa w'); - if (oldPath.toLowerCase() != newPath.toLowerCase() && fs_1.default.existsSync(newPath)) { - let overwrite = await this.showPrompt(`${newPath} exists, overwrite?`); - if (!overwrite) - return; - fs_1.default.unlinkSync(newPath); - } - fs_1.default.renameSync(oldPath, newPath); - } - let filepath = fs_2.isParentFolder(cwd, newPath) ? path_1.default.relative(cwd, newPath) : newPath; - let view = await nvim.call('winsaveview'); - nvim.pauseNotification(); - if (oldPath.toLowerCase() == newPath.toLowerCase()) { - nvim.command(`keepalt ${bufnr}bwipeout!`, true); - nvim.call('coc#util#open_file', ['keepalt edit', filepath], true); - } - else { - nvim.call('coc#util#open_file', ['keepalt edit', filepath], true); - nvim.command(`${bufnr}bwipeout!`, true); - } - if (!exists && lines.join('\n') != '\n') { - nvim.call('append', [0, lines], true); - nvim.command('normal! Gdd', true); - } - nvim.call('winrestview', [view], true); - await nvim.resumeNotification(); - } - setMessageLevel() { - let config = this.getConfiguration('coc.preferences'); - let level = config.get('messageLevel', 'more'); - switch (level) { - case 'error': - this.messageLevel = types_1.MessageLevel.Error; - break; - case 'warning': - this.messageLevel = types_1.MessageLevel.Warning; - break; - default: - this.messageLevel = types_1.MessageLevel.More; - } - } - get folderPaths() { - return this.workspaceFolders.map(f => vscode_uri_1.URI.parse(f.uri).fsPath); - } - get floatSupported() { - let { env } = this; - return env.floating || env.textprop; - } - removeWorkspaceFolder(fsPath) { - let idx = this._workspaceFolders.findIndex(f => vscode_uri_1.URI.parse(f.uri).fsPath == fsPath); - if (idx != -1) { - let folder = this._workspaceFolders[idx]; - this._workspaceFolders.splice(idx, 1); - this._onDidChangeWorkspaceFolders.fire({ - removed: [folder], - added: [] - }); - } - } - renameWorkspaceFolder(oldPath, newPath) { - let idx = this._workspaceFolders.findIndex(f => vscode_uri_1.URI.parse(f.uri).fsPath == oldPath); - if (idx == -1) - return; - let removed = this._workspaceFolders[idx]; - let added = { - uri: vscode_uri_1.URI.file(newPath).toString(), - name: path_1.default.dirname(newPath) - }; - this._workspaceFolders.splice(idx, 1); - this._workspaceFolders.push(added); - this._onDidChangeWorkspaceFolders.fire({ - removed: [removed], - added: [added] - }); - } - addRootPattern(filetype, rootPatterns) { - let patterns = this.rootPatterns.get(filetype) || []; - for (let p of rootPatterns) { - if (!patterns.includes(p)) { - patterns.push(p); - } - } - this.rootPatterns.set(filetype, patterns); - } - get insertMode() { - return this._insertMode; - } - addWorkspaceFolder(rootPath) { - if (rootPath == os_1.default.homedir()) - return; - let { _workspaceFolders } = this; - let uri = vscode_uri_1.URI.file(rootPath).toString(); - let workspaceFolder = { uri, name: path_1.default.basename(rootPath) }; - if (_workspaceFolders.findIndex(o => o.uri == uri) == -1) { - _workspaceFolders.push(workspaceFolder); - if (this._initialized) { - this._onDidChangeWorkspaceFolders.fire({ - added: [workspaceFolder], - removed: [] - }); - } - } - return workspaceFolder; - } - getServerRootPatterns(filetype) { - let lspConfig = this.getConfiguration().get('languageserver', {}); - let patterns = []; - for (let key of Object.keys(lspConfig)) { - let config = lspConfig[key]; - let { filetypes, rootPatterns } = config; - if (filetypes && rootPatterns && filetypes.includes(filetype)) { - patterns.push(...rootPatterns); - } - } - patterns = patterns.concat(this.rootPatterns.get(filetype) || []); - return patterns.length ? array_1.distinct(patterns) : null; - } -} -exports.Workspace = Workspace; -exports.default = new Workspace(); -//# sourceMappingURL=workspace.js.map - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - -/** - * Module variables. - * @private - */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ - -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} - -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - - return str + unitSeparator + unit; -} - -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ - -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - return Math.floor(map[unit] * floatValue); -} - - -/***/ }), -/* 271 */ -/***/ (function(module, exports) { - -/** - * This library modifies the diff-patch-match library by Neil Fraser - * by removing the patch and match functionality and certain advanced - * options in the diff function. The original license is as follows: - * - * === - * - * Diff Match and Patch - * - * Copyright 2006 Google Inc. - * http://code.google.com/p/google-diff-match-patch/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/** - * The data structure representing a diff is an array of tuples: - * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] - * which means: delete 'Hello', add 'Goodbye' and keep ' world.' - */ -var DIFF_DELETE = -1; -var DIFF_INSERT = 1; -var DIFF_EQUAL = 0; - - -/** - * Find the differences between two texts. Simplifies the problem by stripping - * any common prefix or suffix off the texts before diffing. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {Int|Object} [cursor_pos] Edit position in text1 or object with more info - * @return {Array} Array of diff tuples. - */ -function diff_main(text1, text2, cursor_pos, _fix_unicode) { - // Check for equality - if (text1 === text2) { - if (text1) { - return [[DIFF_EQUAL, text1]]; - } - return []; - } - - if (cursor_pos != null) { - var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos); - if (editdiff) { - return editdiff; - } - } - - // Trim off common prefix (speedup). - var commonlength = diff_commonPrefix(text1, text2); - var commonprefix = text1.substring(0, commonlength); - text1 = text1.substring(commonlength); - text2 = text2.substring(commonlength); - - // Trim off common suffix (speedup). - commonlength = diff_commonSuffix(text1, text2); - var commonsuffix = text1.substring(text1.length - commonlength); - text1 = text1.substring(0, text1.length - commonlength); - text2 = text2.substring(0, text2.length - commonlength); - - // Compute the diff on the middle block. - var diffs = diff_compute_(text1, text2); - - // Restore the prefix and suffix. - if (commonprefix) { - diffs.unshift([DIFF_EQUAL, commonprefix]); - } - if (commonsuffix) { - diffs.push([DIFF_EQUAL, commonsuffix]); - } - diff_cleanupMerge(diffs, _fix_unicode); - return diffs; -}; - - -/** - * Find the differences between two texts. Assumes that the texts do not - * have any common prefix or suffix. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @return {Array} Array of diff tuples. - */ -function diff_compute_(text1, text2) { - var diffs; - - if (!text1) { - // Just add some text (speedup). - return [[DIFF_INSERT, text2]]; - } - - if (!text2) { - // Just delete some text (speedup). - return [[DIFF_DELETE, text1]]; - } - - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - var i = longtext.indexOf(shorttext); - if (i !== -1) { - // Shorter text is inside the longer text (speedup). - diffs = [ - [DIFF_INSERT, longtext.substring(0, i)], - [DIFF_EQUAL, shorttext], - [DIFF_INSERT, longtext.substring(i + shorttext.length)] - ]; - // Swap insertions for deletions if diff is reversed. - if (text1.length > text2.length) { - diffs[0][0] = diffs[2][0] = DIFF_DELETE; - } - return diffs; - } - - if (shorttext.length === 1) { - // Single character string. - // After the previous speedup, the character can't be an equality. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - } - - // Check to see if the problem can be split in two. - var hm = diff_halfMatch_(text1, text2); - if (hm) { - // A half-match was found, sort out the return data. - var text1_a = hm[0]; - var text1_b = hm[1]; - var text2_a = hm[2]; - var text2_b = hm[3]; - var mid_common = hm[4]; - // Send both pairs off for separate processing. - var diffs_a = diff_main(text1_a, text2_a); - var diffs_b = diff_main(text1_b, text2_b); - // Merge the results. - return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); - } - - return diff_bisect_(text1, text2); -}; - - -/** - * Find the 'middle snake' of a diff, split the problem in two - * and return the recursively constructed diff. - * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @return {Array} Array of diff tuples. - * @private - */ -function diff_bisect_(text1, text2) { - // Cache the text lengths to prevent multiple calls. - var text1_length = text1.length; - var text2_length = text2.length; - var max_d = Math.ceil((text1_length + text2_length) / 2); - var v_offset = max_d; - var v_length = 2 * max_d; - var v1 = new Array(v_length); - var v2 = new Array(v_length); - // Setting all elements to -1 is faster in Chrome & Firefox than mixing - // integers and undefined. - for (var x = 0; x < v_length; x++) { - v1[x] = -1; - v2[x] = -1; - } - v1[v_offset + 1] = 0; - v2[v_offset + 1] = 0; - var delta = text1_length - text2_length; - // If the total number of characters is odd, then the front path will collide - // with the reverse path. - var front = (delta % 2 !== 0); - // Offsets for start and end of k loop. - // Prevents mapping of space beyond the grid. - var k1start = 0; - var k1end = 0; - var k2start = 0; - var k2end = 0; - for (var d = 0; d < max_d; d++) { - // Walk the front path one step. - for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { - var k1_offset = v_offset + k1; - var x1; - if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) { - x1 = v1[k1_offset + 1]; - } else { - x1 = v1[k1_offset - 1] + 1; - } - var y1 = x1 - k1; - while ( - x1 < text1_length && y1 < text2_length && - text1.charAt(x1) === text2.charAt(y1) - ) { - x1++; - y1++; - } - v1[k1_offset] = x1; - if (x1 > text1_length) { - // Ran off the right of the graph. - k1end += 2; - } else if (y1 > text2_length) { - // Ran off the bottom of the graph. - k1start += 2; - } else if (front) { - var k2_offset = v_offset + delta - k1; - if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) { - // Mirror x2 onto top-left coordinate system. - var x2 = text1_length - v2[k2_offset]; - if (x1 >= x2) { - // Overlap detected. - return diff_bisectSplit_(text1, text2, x1, y1); - } - } - } - } - - // Walk the reverse path one step. - for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { - var k2_offset = v_offset + k2; - var x2; - if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) { - x2 = v2[k2_offset + 1]; - } else { - x2 = v2[k2_offset - 1] + 1; - } - var y2 = x2 - k2; - while ( - x2 < text1_length && y2 < text2_length && - text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1) - ) { - x2++; - y2++; - } - v2[k2_offset] = x2; - if (x2 > text1_length) { - // Ran off the left of the graph. - k2end += 2; - } else if (y2 > text2_length) { - // Ran off the top of the graph. - k2start += 2; - } else if (!front) { - var k1_offset = v_offset + delta - k2; - if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) { - var x1 = v1[k1_offset]; - var y1 = v_offset + x1 - k1_offset; - // Mirror x2 onto top-left coordinate system. - x2 = text1_length - x2; - if (x1 >= x2) { - // Overlap detected. - return diff_bisectSplit_(text1, text2, x1, y1); - } - } - } - } - } - // Diff took too long and hit the deadline or - // number of diffs equals number of characters, no commonality at all. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; -}; - - -/** - * Given the location of the 'middle snake', split the diff in two parts - * and recurse. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} x Index of split point in text1. - * @param {number} y Index of split point in text2. - * @return {Array} Array of diff tuples. - */ -function diff_bisectSplit_(text1, text2, x, y) { - var text1a = text1.substring(0, x); - var text2a = text2.substring(0, y); - var text1b = text1.substring(x); - var text2b = text2.substring(y); - - // Compute both diffs serially. - var diffs = diff_main(text1a, text2a); - var diffsb = diff_main(text1b, text2b); - - return diffs.concat(diffsb); -}; - - -/** - * Determine the common prefix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the start of each - * string. - */ -function diff_commonPrefix(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { - return 0; - } - // Binary search. - // Performance analysis: http://neil.fraser.name/news/2007/10/09/ - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerstart = 0; - while (pointermin < pointermid) { - if ( - text1.substring(pointerstart, pointermid) == - text2.substring(pointerstart, pointermid) - ) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - - if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) { - pointermid--; - } - - return pointermid; -}; - - -/** - * Determine the common suffix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the end of each string. - */ -function diff_commonSuffix(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) { - return 0; - } - // Binary search. - // Performance analysis: http://neil.fraser.name/news/2007/10/09/ - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerend = 0; - while (pointermin < pointermid) { - if ( - text1.substring(text1.length - pointermid, text1.length - pointerend) == - text2.substring(text2.length - pointermid, text2.length - pointerend) - ) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - - if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) { - pointermid--; - } - - return pointermid; -}; - - -/** - * Do the two texts share a substring which is at least half the length of the - * longer text? - * This speedup can produce non-minimal diffs. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {Array.} Five element Array, containing the prefix of - * text1, the suffix of text1, the prefix of text2, the suffix of - * text2 and the common middle. Or null if there was no match. - */ -function diff_halfMatch_(text1, text2) { - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { - return null; // Pointless. - } - - /** - * Does a substring of shorttext exist within longtext such that the substring - * is at least half the length of longtext? - * Closure, but does not reference any external variables. - * @param {string} longtext Longer string. - * @param {string} shorttext Shorter string. - * @param {number} i Start index of quarter length substring within longtext. - * @return {Array.} Five element Array, containing the prefix of - * longtext, the suffix of longtext, the prefix of shorttext, the suffix - * of shorttext and the common middle. Or null if there was no match. - * @private - */ - function diff_halfMatchI_(longtext, shorttext, i) { - // Start with a 1/4 length substring at position i as a seed. - var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); - var j = -1; - var best_common = ''; - var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; - while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { - var prefixLength = diff_commonPrefix( - longtext.substring(i), shorttext.substring(j)); - var suffixLength = diff_commonSuffix( - longtext.substring(0, i), shorttext.substring(0, j)); - if (best_common.length < suffixLength + prefixLength) { - best_common = shorttext.substring( - j - suffixLength, j) + shorttext.substring(j, j + prefixLength); - best_longtext_a = longtext.substring(0, i - suffixLength); - best_longtext_b = longtext.substring(i + prefixLength); - best_shorttext_a = shorttext.substring(0, j - suffixLength); - best_shorttext_b = shorttext.substring(j + prefixLength); - } - } - if (best_common.length * 2 >= longtext.length) { - return [ - best_longtext_a, best_longtext_b, - best_shorttext_a, best_shorttext_b, best_common - ]; - } else { - return null; - } - } - - // First check if the second quarter is the seed for a half-match. - var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); - // Check again based on the third quarter. - var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); - var hm; - if (!hm1 && !hm2) { - return null; - } else if (!hm2) { - hm = hm1; - } else if (!hm1) { - hm = hm2; - } else { - // Both matched. Select the longest. - hm = hm1[4].length > hm2[4].length ? hm1 : hm2; - } - - // A half-match was found, sort out the return data. - var text1_a, text1_b, text2_a, text2_b; - if (text1.length > text2.length) { - text1_a = hm[0]; - text1_b = hm[1]; - text2_a = hm[2]; - text2_b = hm[3]; - } else { - text2_a = hm[0]; - text2_b = hm[1]; - text1_a = hm[2]; - text1_b = hm[3]; - } - var mid_common = hm[4]; - return [text1_a, text1_b, text2_a, text2_b, mid_common]; -}; - - -/** - * Reorder and merge like edit sections. Merge equalities. - * Any edit section can move as long as it doesn't cross an equality. - * @param {Array} diffs Array of diff tuples. - * @param {boolean} fix_unicode Whether to normalize to a unicode-correct diff - */ -function diff_cleanupMerge(diffs, fix_unicode) { - diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ''; - var text_insert = ''; - var commonlength; - while (pointer < diffs.length) { - if (pointer < diffs.length - 1 && !diffs[pointer][1]) { - diffs.splice(pointer, 1); - continue; - } - switch (diffs[pointer][0]) { - case DIFF_INSERT: - - count_insert++; - text_insert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - var previous_equality = pointer - count_insert - count_delete - 1; - if (fix_unicode) { - // prevent splitting of unicode surrogate pairs. when fix_unicode is true, - // we assume that the old and new text in the diff are complete and correct - // unicode-encoded JS strings, but the tuple boundaries may fall between - // surrogate pairs. we fix this by shaving off stray surrogates from the end - // of the previous equality and the beginning of this equality. this may create - // empty equalities or a common prefix or suffix. for example, if AB and AC are - // emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and - // inserting 'AC', and then the common suffix 'AC' will be eliminated. in this - // particular case, both equalities go away, we absorb any previous inequalities, - // and we keep scanning for the next equality before rewriting the tuples. - if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) { - var stray = diffs[previous_equality][1].slice(-1); - diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1); - text_delete = stray + text_delete; - text_insert = stray + text_insert; - if (!diffs[previous_equality][1]) { - // emptied out previous equality, so delete it and include previous delete/insert - diffs.splice(previous_equality, 1); - pointer--; - var k = previous_equality - 1; - if (diffs[k] && diffs[k][0] === DIFF_INSERT) { - count_insert++; - text_insert = diffs[k][1] + text_insert; - k--; - } - if (diffs[k] && diffs[k][0] === DIFF_DELETE) { - count_delete++; - text_delete = diffs[k][1] + text_delete; - k--; - } - previous_equality = k; - } - } - if (starts_with_pair_end(diffs[pointer][1])) { - var stray = diffs[pointer][1].charAt(0); - diffs[pointer][1] = diffs[pointer][1].slice(1); - text_delete += stray; - text_insert += stray; - } - } - if (pointer < diffs.length - 1 && !diffs[pointer][1]) { - // for empty equality not at end, wait for next equality - diffs.splice(pointer, 1); - break; - } - if (text_delete.length > 0 || text_insert.length > 0) { - // note that diff_commonPrefix and diff_commonSuffix are unicode-aware - if (text_delete.length > 0 && text_insert.length > 0) { - // Factor out any common prefixes. - commonlength = diff_commonPrefix(text_insert, text_delete); - if (commonlength !== 0) { - if (previous_equality >= 0) { - diffs[previous_equality][1] += text_insert.substring(0, commonlength); - } else { - diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); - pointer++; - } - text_insert = text_insert.substring(commonlength); - text_delete = text_delete.substring(commonlength); - } - // Factor out any common suffixes. - commonlength = diff_commonSuffix(text_insert, text_delete); - if (commonlength !== 0) { - diffs[pointer][1] = - text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; - text_insert = text_insert.substring(0, text_insert.length - commonlength); - text_delete = text_delete.substring(0, text_delete.length - commonlength); - } - } - // Delete the offending records and add the merged ones. - var n = count_insert + count_delete; - if (text_delete.length === 0 && text_insert.length === 0) { - diffs.splice(pointer - n, n); - pointer = pointer - n; - } else if (text_delete.length === 0) { - diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]); - pointer = pointer - n + 1; - } else if (text_insert.length === 0) { - diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]); - pointer = pointer - n + 1; - } else { - diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); - pointer = pointer - n + 2; - } - } - if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { - // Merge this equality with the previous one. - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ''; - text_insert = ''; - break; - } - } - if (diffs[diffs.length - 1][1] === '') { - diffs.pop(); // Remove the dummy entry at the end. - } - - // Second pass: look for single edits surrounded on both sides by equalities - // which can be shifted sideways to eliminate an equality. - // e.g: ABAC -> ABAC - var changes = false; - pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] === DIFF_EQUAL && - diffs[pointer + 1][0] === DIFF_EQUAL) { - // This is a single edit surrounded by equalities. - if (diffs[pointer][1].substring(diffs[pointer][1].length - - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { - // Shift the edit over the previous equality. - diffs[pointer][1] = diffs[pointer - 1][1] + - diffs[pointer][1].substring(0, diffs[pointer][1].length - - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == - diffs[pointer + 1][1]) { - // Shift the edit over the next equality. - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = - diffs[pointer][1].substring(diffs[pointer + 1][1].length) + - diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } - } - pointer++; - } - // If shifts were made, the diff needs reordering and another shift sweep. - if (changes) { - diff_cleanupMerge(diffs, fix_unicode); - } -}; - -function is_surrogate_pair_start(charCode) { - return charCode >= 0xD800 && charCode <= 0xDBFF; -} - -function is_surrogate_pair_end(charCode) { - return charCode >= 0xDC00 && charCode <= 0xDFFF; -} - -function starts_with_pair_end(str) { - return is_surrogate_pair_end(str.charCodeAt(0)); -} - -function ends_with_pair_start(str) { - return is_surrogate_pair_start(str.charCodeAt(str.length - 1)); -} - -function remove_empty_tuples(tuples) { - var ret = []; - for (var i = 0; i < tuples.length; i++) { - if (tuples[i][1].length > 0) { - ret.push(tuples[i]); - } - } - return ret; -} - -function make_edit_splice(before, oldMiddle, newMiddle, after) { - if (ends_with_pair_start(before) || starts_with_pair_end(after)) { - return null; - } - return remove_empty_tuples([ - [DIFF_EQUAL, before], - [DIFF_DELETE, oldMiddle], - [DIFF_INSERT, newMiddle], - [DIFF_EQUAL, after] - ]); -} - -function find_cursor_edit_diff(oldText, newText, cursor_pos) { - // note: this runs after equality check has ruled out exact equality - var oldRange = typeof cursor_pos === 'number' ? - { index: cursor_pos, length: 0 } : cursor_pos.oldRange; - var newRange = typeof cursor_pos === 'number' ? - null : cursor_pos.newRange; - // take into account the old and new selection to generate the best diff - // possible for a text edit. for example, a text change from "xxx" to "xx" - // could be a delete or forwards-delete of any one of the x's, or the - // result of selecting two of the x's and typing "x". - var oldLength = oldText.length; - var newLength = newText.length; - if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) { - // see if we have an insert or delete before or after cursor - var oldCursor = oldRange.index; - var oldBefore = oldText.slice(0, oldCursor); - var oldAfter = oldText.slice(oldCursor); - var maybeNewCursor = newRange ? newRange.index : null; - editBefore: { - // is this an insert or delete right before oldCursor? - var newCursor = oldCursor + newLength - oldLength; - if (maybeNewCursor !== null && maybeNewCursor !== newCursor) { - break editBefore; - } - if (newCursor < 0 || newCursor > newLength) { - break editBefore; - } - var newBefore = newText.slice(0, newCursor); - var newAfter = newText.slice(newCursor); - if (newAfter !== oldAfter) { - break editBefore; - } - var prefixLength = Math.min(oldCursor, newCursor); - var oldPrefix = oldBefore.slice(0, prefixLength); - var newPrefix = newBefore.slice(0, prefixLength); - if (oldPrefix !== newPrefix) { - break editBefore; - } - var oldMiddle = oldBefore.slice(prefixLength); - var newMiddle = newBefore.slice(prefixLength); - return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter); - } - editAfter: { - // is this an insert or delete right after oldCursor? - if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) { - break editAfter; - } - var cursor = oldCursor; - var newBefore = newText.slice(0, cursor); - var newAfter = newText.slice(cursor); - if (newBefore !== oldBefore) { - break editAfter; - } - var suffixLength = Math.min(oldLength - cursor, newLength - cursor); - var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength); - var newSuffix = newAfter.slice(newAfter.length - suffixLength); - if (oldSuffix !== newSuffix) { - break editAfter; - } - var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength); - var newMiddle = newAfter.slice(0, newAfter.length - suffixLength); - return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix); - } - } - if (oldRange.length > 0 && newRange && newRange.length === 0) { - replaceRange: { - // see if diff could be a splice of the old selection range - var oldPrefix = oldText.slice(0, oldRange.index); - var oldSuffix = oldText.slice(oldRange.index + oldRange.length); - var prefixLength = oldPrefix.length; - var suffixLength = oldSuffix.length; - if (newLength < prefixLength + suffixLength) { - break replaceRange; - } - var newPrefix = newText.slice(0, prefixLength); - var newSuffix = newText.slice(newLength - suffixLength); - if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) { - break replaceRange; - } - var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength); - var newMiddle = newText.slice(prefixLength, newLength - suffixLength); - return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix); - } - } - - return null; -} - -function diff(text1, text2, cursor_pos) { - // only pass fix_unicode=true at the top level, not when diff_main is - // recursively invoked - return diff_main(text1, text2, cursor_pos, true); -} - -diff.INSERT = DIFF_INSERT; -diff.DELETE = DIFF_DELETE; -diff.EQUAL = DIFF_EQUAL; - -module.exports = diff; - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - -const optsArg = __webpack_require__(273) -const pathArg = __webpack_require__(274) - -const {mkdirpNative, mkdirpNativeSync} = __webpack_require__(275) -const {mkdirpManual, mkdirpManualSync} = __webpack_require__(277) -const {useNative, useNativeSync} = __webpack_require__(278) - - -const mkdirp = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNative(opts) - ? mkdirpNative(path, opts) - : mkdirpManual(path, opts) -} - -const mkdirpSync = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNativeSync(opts) - ? mkdirpNativeSync(path, opts) - : mkdirpManualSync(path, opts) -} - -mkdirp.sync = mkdirpSync -mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) -mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) -mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) -mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) - -module.exports = mkdirp - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - -const { promisify } = __webpack_require__(74) -const fs = __webpack_require__(66) -const optsArg = opts => { - if (!opts) - opts = { mode: 0o777, fs } - else if (typeof opts === 'object') - opts = { mode: 0o777, fs, ...opts } - else if (typeof opts === 'number') - opts = { mode: opts, fs } - else if (typeof opts === 'string') - opts = { mode: parseInt(opts, 8), fs } - else - throw new TypeError('invalid options argument') - - opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir - opts.mkdirAsync = promisify(opts.mkdir) - opts.stat = opts.stat || opts.fs.stat || fs.stat - opts.statAsync = promisify(opts.stat) - opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync - opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync - return opts -} -module.exports = optsArg - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - -const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform -const { resolve, parse } = __webpack_require__(82) -const pathArg = path => { - if (/\0/.test(path)) { - // simulate same failure that node raises - throw Object.assign( - new TypeError('path must be a string without null bytes'), - { - path, - code: 'ERR_INVALID_ARG_VALUE', - } - ) - } - - path = resolve(path) - if (platform === 'win32') { - const badWinChars = /[*|"<>?:]/ - const {root} = parse(path) - if (badWinChars.test(path.substr(root.length))) { - throw Object.assign(new Error('Illegal characters in path.'), { - path, - code: 'EINVAL', - }) - } - } - - return path -} -module.exports = pathArg - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - -const {dirname} = __webpack_require__(82) -const {findMade, findMadeSync} = __webpack_require__(276) -const {mkdirpManual, mkdirpManualSync} = __webpack_require__(277) - -const mkdirpNative = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirAsync(path, opts) - - return findMade(opts, path).then(made => - opts.mkdirAsync(path, opts).then(() => made) - .catch(er => { - if (er.code === 'ENOENT') - return mkdirpManual(path, opts) - else - throw er - })) -} - -const mkdirpNativeSync = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirSync(path, opts) - - const made = findMadeSync(opts, path) - try { - opts.mkdirSync(path, opts) - return made - } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts) - else - throw er - } -} - -module.exports = {mkdirpNative, mkdirpNativeSync} - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - -const {dirname} = __webpack_require__(82) - -const findMade = (opts, parent, path = undefined) => { - // we never want the 'made' return value to be a root directory - if (path === parent) - return Promise.resolve() - - return opts.statAsync(parent).then( - st => st.isDirectory() ? path : undefined, // will fail later - er => er.code === 'ENOENT' - ? findMade(opts, dirname(parent), parent) - : undefined - ) -} - -const findMadeSync = (opts, parent, path = undefined) => { - if (path === parent) - return undefined - - try { - return opts.statSync(parent).isDirectory() ? path : undefined - } catch (er) { - return er.code === 'ENOENT' - ? findMadeSync(opts, dirname(parent), parent) - : undefined - } -} - -module.exports = {findMade, findMadeSync} - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - -const {dirname} = __webpack_require__(82) - -const mkdirpManual = (path, opts, made) => { - opts.recursive = false - const parent = dirname(path) - if (parent === path) { - return opts.mkdirAsync(path, opts).catch(er => { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - }) - } - - return opts.mkdirAsync(path, opts).then(() => made || path, er => { - if (er.code === 'ENOENT') - return mkdirpManual(parent, opts) - .then(made => mkdirpManual(path, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - return opts.statAsync(path).then(st => { - if (st.isDirectory()) - return made - else - throw er - }, () => { throw er }) - }) -} - -const mkdirpManualSync = (path, opts, made) => { - const parent = dirname(path) - opts.recursive = false - - if (parent === path) { - try { - return opts.mkdirSync(path, opts) - } catch (er) { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - else - return - } - } - - try { - opts.mkdirSync(path, opts) - return made || path - } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - try { - if (!opts.statSync(path).isDirectory()) - throw er - } catch (_) { - throw er - } - } -} - -module.exports = {mkdirpManual, mkdirpManualSync} - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - -const fs = __webpack_require__(66) - -const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version -const versArr = version.replace(/^v/, '').split('.') -const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 - -const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir -const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync - -module.exports = {useNative, useNativeSync} - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - -const assert = __webpack_require__(108) -const path = __webpack_require__(82) -const fs = __webpack_require__(66) -let glob = undefined -try { - glob = __webpack_require__(280) -} catch (_err) { - // treat glob as optional. -} - -const defaultGlobOpts = { - nosort: true, - silent: true -} - -// for EMFILE handling -let timeout = 0 - -const isWindows = (process.platform === "win32") - -const defaults = options => { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} - -const rimraf = (p, options, cb) => { - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - let busyTries = 0 - let errState = null - let n = 0 - - const next = (er) => { - errState = errState || er - if (--n === 0) - cb(errState) - } - - const afterGlob = (er, results) => { - if (er) - return cb(er) - - n = results.length - if (n === 0) - return cb() - - results.forEach(p => { - const CB = (er) => { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) - } - - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(() => rimraf_(p, options, CB), timeout ++) - } - - // already gone - if (er.code === "ENOENT") er = null - } - - timeout = 0 - next(er) - } - rimraf_(p, options, CB) - }) - } - - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) - - options.lstat(p, (er, stat) => { - if (!er) - return afterGlob(null, [p]) - - glob(p, options.glob, afterGlob) - }) - -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -const rimraf_ = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") - return cb(null) - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) - - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) - - options.unlink(p, er => { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) -} - -const fixWinEPERM = (p, options, er, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.chmod(p, 0o666, er2 => { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, (er3, stats) => { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} - -const fixWinEPERMSync = (p, options, er) => { - assert(p) - assert(options) - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } - - let stats - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } - - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} - -const rmdir = (p, options, originalEr, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} - -const rmkids = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, (er, files) => { - if (er) - return cb(er) - let n = files.length - if (n === 0) - return options.rmdir(p, cb) - let errState - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -const rimrafSync = (p, options) => { - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - let results - - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } - } - - if (!results.length) - return - - for (let i = 0; i < results.length; i++) { - const p = results[i] - - let st - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er - - rmdirSync(p, options, er) - } - } -} - -const rmdirSync = (p, options, originalEr) => { - assert(p) - assert(options) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } -} - -const rmkidsSync = (p, options) => { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const retries = isWindows ? 100 : 1 - let i = 0 - do { - let threw = true - try { - const ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) -} - -module.exports = rimraf -rimraf.sync = rimrafSync - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - -module.exports = glob - -var fs = __webpack_require__(66) -var rp = __webpack_require__(281) -var minimatch = __webpack_require__(283) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(287) -var EE = __webpack_require__(198).EventEmitter -var path = __webpack_require__(82) -var assert = __webpack_require__(108) -var isAbsolute = __webpack_require__(289) -var globSync = __webpack_require__(290) -var common = __webpack_require__(291) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(292) -var util = __webpack_require__(74) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored - -var once = __webpack_require__(294) - -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} - - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } - - return new Glob(pattern, options, cb) -} - -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync - -// old api surface -glob.glob = glob - -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } - - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin -} - -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - - var g = new Glob(pattern, options) - var set = g.minimatch.set - - if (!pattern) - return false - - if (set.length > 1) - return true - - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } - - return false -} - -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length - - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) - - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } - - var self = this - this._processing = 0 - - this._emitQueue = [] - this._processQueue = [] - this.paused = false - - if (this.noprocess) - return this - - if (n === 0) - return done() - - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false - - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } - } -} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - - common.finish(this) - this.emit('end', this.found) -} - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true - - var n = this.matches.length - if (n === 0) - return this._finish() - - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) - - function next () { - if (--n === 0) - self._finish() - } -} - -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - - var found = Object.keys(matchset) - var self = this - var n = found.length - - if (n === 0) - return cb() - - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here - - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} - -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} - -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} - -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } -} - -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - - if (this.aborted) - return - - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } - - //console.error('PROCESS %d', this._processing, pattern) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} - -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} - -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() -} - -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - - var abs = isAbsolute(e) ? e : this._makeAbs(e) - - if (this.mark) - e = this._mark(e) - - if (this.absolute) - e = abs - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) - - this.emit('match', e) -} - -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) - - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - - if (lstatcb) - fs.lstat(abs, lstatcb) - - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() - - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return - - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() - - if (Array.isArray(c)) - return cb(null, c) - } - - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) -} - -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} - -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return - - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - - this.cache[abs] = entries - return cb(null, entries) -} - -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } - - return cb() -} - -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} - - -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) - - var isSym = this.symlinks[abs] - var len = entries.length - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) - } - - cb() -} - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) - - if (needDir && c === 'FILE') - return cb() - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } - - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return cb() - - return cb(null, c, stat) -} - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __webpack_require__(66) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(282) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} - -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } - - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) -} - -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } - } -} - -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} - -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var pathModule = __webpack_require__(82); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(66); - -// JavaScript implementation of realpath, ported from node pre-v6 - -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; - - return callback; - - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } - } - - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } - } -} - -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} - -var normalize = pathModule.normalize; - -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} - -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} - -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } - - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } - - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } - - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } - - return fs.lstat(base, gotStat); - } - - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } - - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); - - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } - - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = { sep: '/' } -try { - path = __webpack_require__(82) -} catch (er) {} - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(284) - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/ - -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } - - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - - return m -} - -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} - -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } - - // "" only matches "" - if (pattern.trim() === '') return p === '' - - return new Minimatch(pattern, options).match(p) -} - -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } - - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - pattern = pattern.trim() - - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } - - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - - // make the set of regexps etc. - this.make() -} - -Minimatch.prototype.debug = function () {} - -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = console.error - - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) - - this.debug(this.pattern, set) - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) - - this.debug(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} - -Minimatch.prototype.braceExpand = braceExpand - -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } - - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter - - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - -var concatMap = __webpack_require__(285); -var balanced = __webpack_require__(286); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function identity(e) { - return e; -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - - return expansions; -} - - - -/***/ }), -/* 285 */ -/***/ (function(module, exports) { - -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; - } - } - - return result; -} - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - -try { - var util = __webpack_require__(74); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __webpack_require__(288); -} - - -/***/ }), -/* 288 */ -/***/ (function(module, exports) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = globSync -globSync.GlobSync = GlobSync - -var fs = __webpack_require__(66) -var rp = __webpack_require__(281) -var minimatch = __webpack_require__(283) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(280).Glob -var util = __webpack_require__(74) -var path = __webpack_require__(82) -var assert = __webpack_require__(108) -var isAbsolute = __webpack_require__(289) -var common = __webpack_require__(291) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored - -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - return new GlobSync(pattern, options).found -} - -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) - - setopts(this, pattern, options) - - if (this.noprocess) - return this - - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} - -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} - - -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} - - -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return - - var abs = this._makeAbs(e) - - if (this.mark) - e = this._mark(e) - - if (this.absolute) { - e = abs - } - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true - - if (this.stat) - this._stat(e) -} - - -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) - - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } - - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) - - return entries -} - -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries - - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null - - if (Array.isArray(c)) - return c - } - - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} - -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - - this.cache[abs] = entries - - // mark and cache dir-ness - return entries -} - -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} - -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) - - var len = entries.length - var isSym = this.symlinks[abs] - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} - -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) -} - -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } - - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } - } - - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return false - - return c -} - -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} - -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored - -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} - -var path = __webpack_require__(82) -var minimatch = __webpack_require__(283) -var isAbsolute = __webpack_require__(289) -var Minimatch = minimatch.Minimatch - -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - -function alphasort (a, b) { - return a.localeCompare(b) -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || [] - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] - - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} - -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } - - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) - - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } - - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } - } - - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) - - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) - } - } - - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} - -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } - } - - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) - } - - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - - return abs -} - - -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - -var wrappy = __webpack_require__(293) -var reqs = Object.create(null) -var once = __webpack_require__(294) - -module.exports = wrappy(inflight) - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} - -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) - - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} - -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} - - -/***/ }), -/* 293 */ -/***/ (function(module, exports) { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - -var wrappy = __webpack_require__(293) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), -/* 295 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; }); -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -var FullTextDocument = /** @class */ (function () { - function FullTextDocument(uri, languageId, version, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version; - this._content = content; - this._lineOffsets = undefined; - } - Object.defineProperty(FullTextDocument.prototype, "uri", { - get: function () { - return this._uri; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "languageId", { - get: function () { - return this._languageId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "version", { - get: function () { - return this._version; - }, - enumerable: true, - configurable: true - }); - FullTextDocument.prototype.getText = function (range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument.prototype.update = function (changes, version) { - for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { - var change = changes_1[_i]; - if (FullTextDocument.isIncremental(change)) { - // makes sure start is before end - var range = getWellformedRange(change.range); - // update content - var startOffset = this.offsetAt(range.start); - var endOffset = this.offsetAt(range.end); - this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length); - // update the offsets - var startLine = Math.max(range.start.line, 0); - var endLine = Math.max(range.end.line, 0); - var lineOffsets = this._lineOffsets; - var addedLineOffsets = computeLineOffsets(change.text, false, startOffset); - if (endLine - startLine === addedLineOffsets.length) { - for (var i = 0, len = addedLineOffsets.length; i < len; i++) { - lineOffsets[i + startLine + 1] = addedLineOffsets[i]; - } - } - else { - if (addedLineOffsets.length < 10000) { - lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets)); - } - else { // avoid too many arguments for splice - this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1)); - } - } - var diff = change.text.length - (endOffset - startOffset); - if (diff !== 0) { - for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) { - lineOffsets[i] = lineOffsets[i] + diff; - } - } - } - else if (FullTextDocument.isFull(change)) { - this._content = change.text; - this._lineOffsets = undefined; - } - else { - throw new Error('Unknown change event received'); - } - } - this._version = version; - }; - FullTextDocument.prototype.getLineOffsets = function () { - if (this._lineOffsets === undefined) { - this._lineOffsets = computeLineOffsets(this._content, true); - } - return this._lineOffsets; - }; - FullTextDocument.prototype.positionAt = function (offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, high = lineOffsets.length; - if (high === 0) { - return { line: 0, character: offset }; - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } - else { - low = mid + 1; - } - } - // low is the least x for which the line offset is larger than the current offset - // or array.length if no line offset is larger than the current offset - var line = low - 1; - return { line: line, character: offset - lineOffsets[line] }; - }; - FullTextDocument.prototype.offsetAt = function (position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } - else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument.prototype, "lineCount", { - get: function () { - return this.getLineOffsets().length; - }, - enumerable: true, - configurable: true - }); - FullTextDocument.isIncremental = function (event) { - var candidate = event; - return candidate !== undefined && candidate !== null && - typeof candidate.text === 'string' && candidate.range !== undefined && - (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); - }; - FullTextDocument.isFull = function (event) { - var candidate = event; - return candidate !== undefined && candidate !== null && - typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; - }; - return FullTextDocument; -}()); -var TextDocument; -(function (TextDocument) { - /** - * Creates a new text document. - * - * @param uri The document's uri. - * @param languageId The document's language Id. - * @param version The document's initial version number. - * @param content The document's content. - */ - function create(uri, languageId, version, content) { - return new FullTextDocument(uri, languageId, version, content); - } - TextDocument.create = create; - /** - * Updates a TextDocument by modifing its content. - * - * @param document the document to update. Only documents created by TextDocument.create are valid inputs. - * @param changes the changes to apply to the document. - * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter. - * - */ - function update(document, changes, version) { - if (document instanceof FullTextDocument) { - document.update(changes, version); - return document; - } - else { - throw new Error('TextDocument.update: document must be created by TextDocument.create'); - } - } - TextDocument.update = update; - function applyEdits(document, edits) { - var text = document.getText(); - var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = 0; - var spans = []; - for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) { - var e = sortedEdits_1[_i]; - var startOffset = document.offsetAt(e.range.start); - if (startOffset < lastModifiedOffset) { - throw new Error('Overlapping edit'); - } - else if (startOffset > lastModifiedOffset) { - spans.push(text.substring(lastModifiedOffset, startOffset)); - } - if (e.newText.length) { - spans.push(e.newText); - } - lastModifiedOffset = document.offsetAt(e.range.end); - } - spans.push(text.substr(lastModifiedOffset)); - return spans.join(''); - } - TextDocument.applyEdits = applyEdits; -})(TextDocument || (TextDocument = {})); -function mergeSort(data, compare) { - if (data.length <= 1) { - // sorted - return data; - } - var p = (data.length / 2) | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort(left, compare); - mergeSort(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - // smaller_equal -> take left to preserve order - data[i++] = left[leftIdx++]; - } - else { - // greater -> take right - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; -} -function computeLineOffsets(text, isAtLineStart, textOffset) { - if (textOffset === void 0) { textOffset = 0; } - var result = isAtLineStart ? [textOffset] : []; - for (var i = 0; i < text.length; i++) { - var ch = text.charCodeAt(i); - if (ch === 13 /* CarriageReturn */ || ch === 10 /* LineFeed */) { - if (ch === 13 /* CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* LineFeed */) { - i++; - } - result.push(textOffset + i + 1); - } - } - return result; -} -function getWellformedRange(range) { - var start = range.start; - var end = range.end; - if (start.line > end.line || (start.line === end.line && start.character > end.character)) { - return { start: end, end: start }; - } - return range; -} -function getWellformedEdit(textEdit) { - var range = getWellformedRange(textEdit.range); - if (range !== textEdit.range) { - return { newText: textEdit.newText, range: range }; - } - return textEdit; -} - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const types_1 = __webpack_require__(297); -const object_1 = __webpack_require__(249); -const util_1 = __webpack_require__(238); -const configuration_1 = __webpack_require__(298); -const model_1 = __webpack_require__(299); -const util_2 = __webpack_require__(300); -const is_1 = __webpack_require__(250); -const fs_2 = __webpack_require__(306); -const logger = __webpack_require__(64)('configurations'); -function lookUp(tree, key) { - if (key) { - if (tree && tree.hasOwnProperty(key)) - return tree[key]; - const parts = key.split('.'); - let node = tree; - for (let i = 0; node && i < parts.length; i++) { - node = node[parts[i]]; - } - return node; - } - return tree; -} -class Configurations { - constructor(userConfigFile, _proxy) { - this.userConfigFile = userConfigFile; - this._proxy = _proxy; - this._errorItems = []; - this._folderConfigurations = new Map(); - this._onError = new vscode_languageserver_protocol_1.Emitter(); - this._onChange = new vscode_languageserver_protocol_1.Emitter(); - this.disposables = []; - this.onError = this._onError.event; - this.onDidChange = this._onChange.event; - let user = this.parseContentFromFile(userConfigFile); - let data = { - defaults: util_2.loadDefaultConfigurations(), - user, - workspace: { contents: {} } - }; - this._configuration = Configurations.parse(data); - this.watchFile(userConfigFile, types_1.ConfigurationTarget.User); - let folderConfigFile = path_1.default.join(process.cwd(), `.vim/${util_1.CONFIG_FILE_NAME}`); - if (folderConfigFile != userConfigFile && fs_1.default.existsSync(folderConfigFile)) { - this.addFolderFile(folderConfigFile); - } - } - parseContentFromFile(filepath) { - if (!filepath) - return { contents: {} }; - let uri = vscode_uri_1.URI.file(filepath).toString(); - this._errorItems = this._errorItems.filter(o => o.location.uri != uri); - let res = util_2.parseContentFromFile(filepath, errors => { - this._errorItems.push(...errors); - }); - this._onError.fire(this._errorItems); - return res; - } - get errorItems() { - return this._errorItems; - } - get foldConfigurations() { - return this._folderConfigurations; - } - // used for extensions, no change event fired - extendsDefaults(props) { - let { defaults } = this._configuration; - let { contents } = defaults; - contents = object_1.deepClone(contents); - Object.keys(props).forEach(key => { - util_2.addToValueTree(contents, key, props[key], msg => { - logger.error(msg); - }); - }); - let data = { - defaults: { contents }, - user: this._configuration.user, - workspace: this._configuration.workspace - }; - this._configuration = Configurations.parse(data); - } - // change user configuration, without change file - updateUserConfig(props) { - if (!props || Object.keys(props).length == 0) - return; - let { user } = this._configuration; - let model = user.clone(); - Object.keys(props).forEach(key => { - let val = props[key]; - if (val === undefined) { - model.removeValue(key); - } - else if (is_1.objectLiteral(val)) { - for (let k of Object.keys(val)) { - model.setValue(`${key}.${k}`, val[k]); - } - } - else { - model.setValue(key, val); - } - }); - this.changeConfiguration(types_1.ConfigurationTarget.User, model); - } - get defaults() { - return this._configuration.defaults; - } - get user() { - return this._configuration.user; - } - get workspace() { - return this._configuration.workspace; - } - addFolderFile(filepath) { - let { _folderConfigurations } = this; - if (_folderConfigurations.has(filepath)) - return; - if (path_1.default.resolve(filepath, '../..') == os_1.default.homedir()) - return; - let model = this.parseContentFromFile(filepath); - this.watchFile(filepath, types_1.ConfigurationTarget.Workspace); - this.changeConfiguration(types_1.ConfigurationTarget.Workspace, model, filepath); - } - watchFile(filepath, target) { - if (!fs_1.default.existsSync(filepath) || global.hasOwnProperty('__TEST__')) - return; - let disposable = util_1.watchFile(filepath, () => { - let model = this.parseContentFromFile(filepath); - this.changeConfiguration(target, model, filepath); - }); - this.disposables.push(disposable); - } - // create new configuration and fire change event - changeConfiguration(target, model, configFile) { - let { defaults, user, workspace } = this._configuration; - let { workspaceConfigFile } = this; - let data = { - defaults: target == types_1.ConfigurationTarget.Global ? model : defaults, - user: target == types_1.ConfigurationTarget.User ? model : user, - workspace: target == types_1.ConfigurationTarget.Workspace ? model : workspace, - }; - let configuration = Configurations.parse(data); - let changed = util_2.getChangedKeys(this._configuration.getValue(), configuration.getValue()); - if (target == types_1.ConfigurationTarget.Workspace && configFile) { - this._folderConfigurations.set(configFile, new model_1.ConfigurationModel(model.contents)); - this.workspaceConfigFile = configFile; - } - if (changed.length == 0) - return; - this._configuration = configuration; - this._onChange.fire({ - affectsConfiguration: (section, resource) => { - if (!resource || target != types_1.ConfigurationTarget.Workspace) - return changed.includes(section); - let u = vscode_uri_1.URI.parse(resource); - if (u.scheme !== 'file') - return changed.includes(section); - let filepath = u.fsPath; - let preRoot = workspaceConfigFile ? path_1.default.resolve(workspaceConfigFile, '../..') : ''; - if (configFile && !fs_2.isParentFolder(preRoot, filepath, true) && !fs_2.isParentFolder(path_1.default.resolve(configFile, '../..'), filepath)) { - return false; - } - return changed.includes(section); - } - }); - } - setFolderConfiguration(uri) { - let u = vscode_uri_1.URI.parse(uri); - if (u.scheme != 'file') - return; - let filepath = u.fsPath; - for (let [configFile, model] of this.foldConfigurations) { - let root = path_1.default.resolve(configFile, '../..'); - if (fs_2.isParentFolder(root, filepath, true) && this.workspaceConfigFile != configFile) { - this.changeConfiguration(types_1.ConfigurationTarget.Workspace, model, configFile); - break; - } - } - } - hasFolderConfiguration(filepath) { - let { folders } = this; - return folders.findIndex(f => fs_2.isParentFolder(f, filepath, true)) !== -1; - } - getConfigFile(target) { - if (target == types_1.ConfigurationTarget.Global) - return null; - if (target == types_1.ConfigurationTarget.User) - return this.userConfigFile; - return this.workspaceConfigFile; - } - get folders() { - let res = []; - let { _folderConfigurations } = this; - for (let folder of _folderConfigurations.keys()) { - res.push(path_1.default.resolve(folder, '../..')); - } - return res; - } - get configuration() { - return this._configuration; - } - /** - * getConfiguration - * - * @public - * @param {string} section - * @returns {WorkspaceConfiguration} - */ - getConfiguration(section, resource) { - let configuration; - if (resource) { - let { defaults, user } = this._configuration; - configuration = new configuration_1.Configuration(defaults, user, this.getFolderConfiguration(resource)); - } - else { - configuration = this._configuration; - } - const config = Object.freeze(lookUp(configuration.getValue(null), section)); - const result = { - has(key) { - return typeof lookUp(config, key) !== 'undefined'; - }, - get: (key, defaultValue) => { - let result = lookUp(config, key); - if (result == null) - return defaultValue; - return result; - }, - update: (key, value, isUser = false) => { - let s = section ? `${section}.${key}` : key; - let target = isUser ? types_1.ConfigurationTarget.User : types_1.ConfigurationTarget.Workspace; - let model = target == types_1.ConfigurationTarget.User ? this.user.clone() : this.workspace.clone(); - if (value == undefined) { - model.removeValue(s); - } - else { - model.setValue(s, value); - } - if (target == types_1.ConfigurationTarget.Workspace && !this.workspaceConfigFile && this._proxy) { - let file = this.workspaceConfigFile = this._proxy.workspaceConfigFile; - if (!fs_1.default.existsSync(file)) { - let folder = path_1.default.dirname(file); - if (!fs_1.default.existsSync(folder)) - fs_1.default.mkdirSync(folder); - fs_1.default.writeFileSync(file, '{}', { encoding: 'utf8' }); - } - } - this.changeConfiguration(target, model, target == types_1.ConfigurationTarget.Workspace ? this.workspaceConfigFile : this.userConfigFile); - if (this._proxy && !global.hasOwnProperty('__TEST__')) { - if (value == undefined) { - this._proxy.$removeConfigurationOption(target, s); - } - else { - this._proxy.$updateConfigurationOption(target, s, value); - } - } - }, - inspect: (key) => { - key = section ? `${section}.${key}` : key; - const config = this._configuration.inspect(key); - if (config) { - return { - key, - defaultValue: config.default, - globalValue: config.user, - workspaceValue: config.workspace, - }; - } - return undefined; - } - }; - Object.defineProperty(result, 'has', { - enumerable: false - }); - Object.defineProperty(result, 'get', { - enumerable: false - }); - Object.defineProperty(result, 'update', { - enumerable: false - }); - Object.defineProperty(result, 'inspect', { - enumerable: false - }); - if (typeof config === 'object') { - object_1.mixin(result, config, false); - } - return object_1.deepFreeze(result); - } - getFolderConfiguration(uri) { - let u = vscode_uri_1.URI.parse(uri); - if (u.scheme != 'file') - return new model_1.ConfigurationModel(); - let filepath = u.fsPath; - for (let [configFile, model] of this.foldConfigurations) { - let root = path_1.default.resolve(configFile, '../..'); - if (fs_2.isParentFolder(root, filepath, true)) - return model; - } - return new model_1.ConfigurationModel(); - } - checkFolderConfiguration(uri) { - let u = vscode_uri_1.URI.parse(uri); - if (u.scheme != 'file') - return; - let rootPath = path_1.default.dirname(u.fsPath); - if (!this.hasFolderConfiguration(rootPath)) { - let folder = fs_2.findUp('.vim', rootPath); - if (folder && folder != os_1.default.homedir()) { - let file = path_1.default.join(folder, util_1.CONFIG_FILE_NAME); - if (fs_1.default.existsSync(file)) { - this.addFolderFile(file); - } - } - } - else { - this.setFolderConfiguration(uri); - } - } - static parse(data) { - const defaultConfiguration = new model_1.ConfigurationModel(data.defaults.contents); - const userConfiguration = new model_1.ConfigurationModel(data.user.contents); - const workspaceConfiguration = new model_1.ConfigurationModel(data.workspace.contents); - return new configuration_1.Configuration(defaultConfiguration, userConfiguration, workspaceConfiguration, new model_1.ConfigurationModel()); - } - dispose() { - util_1.disposeAll(this.disposables); - } -} -exports.default = Configurations; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServiceStat = exports.DiagnosticKind = exports.ConfigurationTarget = exports.MessageLevel = exports.SourceType = exports.ExtensionType = exports.PatternType = void 0; -var PatternType; -(function (PatternType) { - PatternType[PatternType["Buffer"] = 0] = "Buffer"; - PatternType[PatternType["LanguageServer"] = 1] = "LanguageServer"; - PatternType[PatternType["Global"] = 2] = "Global"; -})(PatternType = exports.PatternType || (exports.PatternType = {})); -var ExtensionType; -(function (ExtensionType) { - ExtensionType[ExtensionType["Global"] = 0] = "Global"; - ExtensionType[ExtensionType["Local"] = 1] = "Local"; - ExtensionType[ExtensionType["SingleFile"] = 2] = "SingleFile"; - ExtensionType[ExtensionType["Internal"] = 3] = "Internal"; -})(ExtensionType = exports.ExtensionType || (exports.ExtensionType = {})); -var SourceType; -(function (SourceType) { - SourceType[SourceType["Native"] = 0] = "Native"; - SourceType[SourceType["Remote"] = 1] = "Remote"; - SourceType[SourceType["Service"] = 2] = "Service"; -})(SourceType = exports.SourceType || (exports.SourceType = {})); -var MessageLevel; -(function (MessageLevel) { - MessageLevel[MessageLevel["More"] = 0] = "More"; - MessageLevel[MessageLevel["Warning"] = 1] = "Warning"; - MessageLevel[MessageLevel["Error"] = 2] = "Error"; -})(MessageLevel = exports.MessageLevel || (exports.MessageLevel = {})); -var ConfigurationTarget; -(function (ConfigurationTarget) { - ConfigurationTarget[ConfigurationTarget["Global"] = 0] = "Global"; - ConfigurationTarget[ConfigurationTarget["User"] = 1] = "User"; - ConfigurationTarget[ConfigurationTarget["Workspace"] = 2] = "Workspace"; -})(ConfigurationTarget = exports.ConfigurationTarget || (exports.ConfigurationTarget = {})); -var DiagnosticKind; -(function (DiagnosticKind) { - DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax"; - DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic"; - DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion"; -})(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {})); -var ServiceStat; -(function (ServiceStat) { - ServiceStat[ServiceStat["Initial"] = 0] = "Initial"; - ServiceStat[ServiceStat["Starting"] = 1] = "Starting"; - ServiceStat[ServiceStat["StartFailed"] = 2] = "StartFailed"; - ServiceStat[ServiceStat["Running"] = 3] = "Running"; - ServiceStat[ServiceStat["Stopping"] = 4] = "Stopping"; - ServiceStat[ServiceStat["Stopped"] = 5] = "Stopped"; -})(ServiceStat = exports.ServiceStat || (exports.ServiceStat = {})); -//# sourceMappingURL=types.js.map - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Configuration = void 0; -const model_1 = __webpack_require__(299); -class Configuration { - constructor(_defaultConfiguration, _userConfiguration, _workspaceConfiguration, _memoryConfiguration = new model_1.ConfigurationModel()) { - this._defaultConfiguration = _defaultConfiguration; - this._userConfiguration = _userConfiguration; - this._workspaceConfiguration = _workspaceConfiguration; - this._memoryConfiguration = _memoryConfiguration; - } - getConsolidateConfiguration() { - if (!this._consolidateConfiguration) { - this._consolidateConfiguration = this._defaultConfiguration.merge(this._userConfiguration, this._workspaceConfiguration, this._memoryConfiguration); - this._consolidateConfiguration = this._consolidateConfiguration.freeze(); - } - return this._consolidateConfiguration; - } - getValue(section) { - let configuration = this.getConsolidateConfiguration(); - return configuration.getValue(section); - } - inspect(key) { - const consolidateConfigurationModel = this.getConsolidateConfiguration(); - const { _workspaceConfiguration, _memoryConfiguration } = this; - return { - default: this._defaultConfiguration.freeze().getValue(key), - user: this._userConfiguration.freeze().getValue(key), - workspace: _workspaceConfiguration.freeze().getValue(key), - memory: _memoryConfiguration.freeze().getValue(key), - value: consolidateConfigurationModel.getValue(key) - }; - } - get defaults() { - return this._defaultConfiguration; - } - get user() { - return this._userConfiguration; - } - get workspace() { - return this._workspaceConfiguration; - } - toData() { - return { - defaults: { - contents: this._defaultConfiguration.contents - }, - user: { - contents: this._userConfiguration.contents - }, - workspace: { - contents: this._workspaceConfiguration.contents - } - }; - } -} -exports.Configuration = Configuration; -//# sourceMappingURL=configuration.js.map - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConfigurationModel = void 0; -const is_1 = __webpack_require__(250); -const object_1 = __webpack_require__(249); -const util_1 = __webpack_require__(300); -class ConfigurationModel { - constructor(_contents = {}) { - this._contents = _contents; - } - get contents() { - return this._contents; - } - clone() { - return new ConfigurationModel(object_1.deepClone(this._contents)); - } - getValue(section) { - let res = section - ? util_1.getConfigurationValue(this.contents, section) - : this.contents; - return res; - } - merge(...others) { - const contents = object_1.deepClone(this.contents); - for (const other of others) { - this.mergeContents(contents, other.contents); - } - return new ConfigurationModel(contents); - } - freeze() { - if (!Object.isFrozen(this._contents)) { - Object.freeze(this._contents); - } - return this; - } - mergeContents(source, target) { - for (const key of Object.keys(target)) { - if (key in source) { - if (is_1.objectLiteral(source[key]) && is_1.objectLiteral(target[key])) { - this.mergeContents(source[key], target[key]); - continue; - } - } - source[key] = object_1.deepClone(target[key]); - } - } - // Update methods - setValue(key, value) { - util_1.addToValueTree(this.contents, key, value, message => { - console.error(message); - }); - } - removeValue(key) { - util_1.removeFromValueTree(this.contents, key); - } -} -exports.ConfigurationModel = ConfigurationModel; -//# sourceMappingURL=model.js.map - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getChangedKeys = exports.getKeys = exports.loadDefaultConfigurations = exports.getConfigurationValue = exports.removeFromValueTree = exports.addToValueTree = exports.convertErrors = exports.parseConfiguration = exports.parseContentFromFile = void 0; -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_languageserver_textdocument_1 = __webpack_require__(295); -const jsonc_parser_1 = __webpack_require__(301); -const is_1 = __webpack_require__(250); -const object_1 = __webpack_require__(249); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const vscode_uri_1 = __webpack_require__(243); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const logger = __webpack_require__(64)('configuration-util'); -const isWebpack = typeof __webpack_require__ === "function"; -const pluginRoot = isWebpack ? path_1.default.dirname(__dirname) : path_1.default.resolve(__dirname, '../..'); -function parseContentFromFile(filepath, onError) { - if (!filepath || !fs_1.default.existsSync(filepath)) - return { contents: {} }; - let content; - let uri = vscode_uri_1.URI.file(filepath).toString(); - try { - content = fs_1.default.readFileSync(filepath, 'utf8'); - } - catch (_e) { - content = ''; - } - let [errors, contents] = parseConfiguration(content); - if (errors && errors.length) { - onError(convertErrors(uri, content, errors)); - } - return { contents }; -} -exports.parseContentFromFile = parseContentFromFile; -function parseConfiguration(content) { - if (content.length == 0) - return [[], {}]; - let errors = []; - let data = jsonc_parser_1.parse(content, errors, { allowTrailingComma: true }); - function addProperty(current, key, remains, value) { - if (remains.length == 0) { - current[key] = convert(value); - } - else { - if (!current[key]) - current[key] = {}; - let o = current[key]; - let first = remains.shift(); - addProperty(o, first, remains, value); - } - } - function convert(obj, split = false) { - if (!is_1.objectLiteral(obj)) - return obj; - if (is_1.emptyObject(obj)) - return {}; - let dest = {}; - for (let key of Object.keys(obj)) { - if (split && key.includes('.')) { - let parts = key.split('.'); - let first = parts.shift(); - addProperty(dest, first, parts, obj[key]); - } - else { - dest[key] = convert(obj[key]); - } - } - return dest; - } - return [errors, convert(data, true)]; -} -exports.parseConfiguration = parseConfiguration; -function convertErrors(uri, content, errors) { - let items = []; - let document = vscode_languageserver_textdocument_1.TextDocument.create(uri, 'json', 0, content); - for (let err of errors) { - let msg = 'parse error'; - switch (err.error) { - case 2: - msg = 'invalid number'; - break; - case 8: - msg = 'close brace expected'; - break; - case 5: - msg = 'colon expected'; - break; - case 6: - msg = 'comma expected'; - break; - case 9: - msg = 'end of file expected'; - break; - case 16: - msg = 'invaliad character'; - break; - case 10: - msg = 'invalid commment token'; - break; - case 15: - msg = 'invalid escape character'; - break; - case 1: - msg = 'invalid symbol'; - break; - case 14: - msg = 'invalid unicode'; - break; - case 3: - msg = 'property name expected'; - break; - case 13: - msg = 'unexpected end of number'; - break; - case 12: - msg = 'unexpected end of string'; - break; - case 11: - msg = 'unexpected end of comment'; - break; - case 4: - msg = 'value expected'; - break; - default: - msg = 'Unknwn error'; - break; - } - let range = { - start: document.positionAt(err.offset), - end: document.positionAt(err.offset + err.length), - }; - let loc = vscode_languageserver_protocol_1.Location.create(uri, range); - items.push({ location: loc, message: msg }); - } - return items; -} -exports.convertErrors = convertErrors; -function addToValueTree(settingsTreeRoot, key, value, conflictReporter) { - const segments = key.split('.'); - const last = segments.pop(); - let curr = settingsTreeRoot; - for (let i = 0; i < segments.length; i++) { - let s = segments[i]; - let obj = curr[s]; - switch (typeof obj) { - case 'function': { - obj = curr[s] = {}; - break; - } - case 'undefined': { - obj = curr[s] = {}; - break; - } - case 'object': - break; - default: - conflictReporter(`Ignoring ${key} as ${segments - .slice(0, i + 1) - .join('.')} is ${JSON.stringify(obj)}`); - return; - } - curr = obj; - } - if (typeof curr === 'object') { - curr[last] = value; // workaround https://github.com/Microsoft/vscode/issues/13606 - } - else { - conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`); - } -} -exports.addToValueTree = addToValueTree; -function removeFromValueTree(valueTree, key) { - const segments = key.split('.'); - doRemoveFromValueTree(valueTree, segments); -} -exports.removeFromValueTree = removeFromValueTree; -function doRemoveFromValueTree(valueTree, segments) { - const first = segments.shift(); - if (segments.length === 0) { - // Reached last segment - delete valueTree[first]; - return; - } - if (Object.keys(valueTree).includes(first)) { - const value = valueTree[first]; - if (typeof value === 'object' && !Array.isArray(value)) { - doRemoveFromValueTree(value, segments); - if (Object.keys(value).length === 0) { - delete valueTree[first]; - } - } - } -} -function getConfigurationValue(config, settingPath, defaultValue) { - function accessSetting(config, path) { - let current = config; - for (let i = 0; i < path.length; i++) { - if (typeof current !== 'object' || current === null) { - return undefined; - } - current = current[path[i]]; - } - return current; - } - const path = settingPath.split('.'); - const result = accessSetting(config, path); - return typeof result === 'undefined' ? defaultValue : result; -} -exports.getConfigurationValue = getConfigurationValue; -function loadDefaultConfigurations() { - let file = path_1.default.join(pluginRoot, 'data/schema.json'); - if (!fs_1.default.existsSync(file)) { - console.error('schema.json not found, reinstall coc.nvim to fix this!'); - return { contents: {} }; - } - let content = fs_1.default.readFileSync(file, 'utf8'); - let { properties } = JSON.parse(content); - let config = {}; - Object.keys(properties).forEach(key => { - let value = properties[key].default; - if (value !== undefined) { - addToValueTree(config, key, value, message => { - logger.error(message); - }); - } - }); - return { contents: config }; -} -exports.loadDefaultConfigurations = loadDefaultConfigurations; -function getKeys(obj, curr) { - let keys = []; - for (let key of Object.keys(obj)) { - let val = obj[key]; - let newKey = curr ? `${curr}.${key}` : key; - keys.push(newKey); - if (is_1.objectLiteral(val)) { - keys.push(...getKeys(val, newKey)); - } - } - return keys; -} -exports.getKeys = getKeys; -function getChangedKeys(from, to) { - let keys = []; - let fromKeys = getKeys(from); - let toKeys = getKeys(to); - const added = toKeys.filter(key => !fromKeys.includes(key)); - const removed = fromKeys.filter(key => !toKeys.includes(key)); - keys.push(...added); - keys.push(...removed); - for (const key of fromKeys) { - if (!toKeys.includes(key)) - continue; - const value1 = getConfigurationValue(from, key); - const value2 = getConfigurationValue(to, key); - if (!object_1.equals(value1, value2)) { - keys.push(key); - } - } - return keys; -} -exports.getChangedKeys = getChangedKeys; -//# sourceMappingURL=util.js.map - -/***/ }), -/* 301 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; }); -/* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(302); -/* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(304); -/* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(303); -/* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(305); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - -/** - * Creates a JSON scanner on the given text. - * If ignoreTrivia is set, whitespaces or comments are ignored. - */ -var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"]; -/** - * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. - */ -var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"]; -/** - * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. - * Therefore, always check the errors list to find out if the input was valid. - */ -var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"]; -/** - * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. - */ -var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"]; -/** - * Finds the node at the given path in a JSON DOM. - */ -var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"]; -/** - * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. - */ -var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"]; -/** - * Gets the JSON path of the given JSON DOM node - */ -var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"]; -/** - * Evaluates the JavaScript object of the given JSON DOM node - */ -var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"]; -/** - * Parses the given text and invokes the visitor functions for each object, array and literal reached. - */ -var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"]; -/** - * Takes JSON with JavaScript-style comments and remove - * them. Optionally replaces every none-newline character - * of comments with a replaceCharacter - */ -var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"]; -function printParseErrorCode(code) { - switch (code) { - case 1 /* InvalidSymbol */: return 'InvalidSymbol'; - case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat'; - case 3 /* PropertyNameExpected */: return 'PropertyNameExpected'; - case 4 /* ValueExpected */: return 'ValueExpected'; - case 5 /* ColonExpected */: return 'ColonExpected'; - case 6 /* CommaExpected */: return 'CommaExpected'; - case 7 /* CloseBraceExpected */: return 'CloseBraceExpected'; - case 8 /* CloseBracketExpected */: return 'CloseBracketExpected'; - case 9 /* EndOfFileExpected */: return 'EndOfFileExpected'; - case 10 /* InvalidCommentToken */: return 'InvalidCommentToken'; - case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; - case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString'; - case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; - case 14 /* InvalidUnicode */: return 'InvalidUnicode'; - case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; - case 16 /* InvalidCharacter */: return 'InvalidCharacter'; - } - return ''; -} -/** - * Computes the edits needed to format a JSON document. - * - * @param documentText The input text - * @param range The range to format or `undefined` to format the full content - * @param options The formatting options - * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or - * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of - * text in the original document. However, multiple edits can have - * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first. - * To apply edits to an input, you can use `applyEdits`. - */ -function format(documentText, range, options) { - return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options); -} -/** - * Computes the edits needed to modify a value in the JSON document. - * - * @param documentText The input text - * @param path The path of the value to change. The path represents either to the document root, a property or an array item. - * If the path points to an non-existing property or item, it will be created. - * @param value The new value for the specified property or item. If the value is undefined, - * the property or item will be removed. - * @param options Options - * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or - * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of - * text in the original document. However, multiple edits can have - * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first. - * To apply edits to an input, you can use `applyEdits`. - */ -function modify(text, path, value, options) { - return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options); -} -/** - * Applies edits to a input string. - */ -function applyEdits(text, edits) { - for (var i = edits.length - 1; i >= 0; i--) { - text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]); - } - return text; -} - - -/***/ }), -/* 302 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; }); -/* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(303); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - -function format(documentText, range, options) { - var initialIndentLevel; - var formatText; - var formatTextStart; - var rangeStart; - var rangeEnd; - if (range) { - rangeStart = range.offset; - rangeEnd = rangeStart + range.length; - formatTextStart = rangeStart; - while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { - formatTextStart--; - } - var endOffset = rangeEnd; - while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { - endOffset++; - } - formatText = documentText.substring(formatTextStart, endOffset); - initialIndentLevel = computeIndentLevel(formatText, options); - } - else { - formatText = documentText; - initialIndentLevel = 0; - formatTextStart = 0; - rangeStart = 0; - rangeEnd = documentText.length; - } - var eol = getEOL(options, documentText); - var lineBreak = false; - var indentLevel = 0; - var indentValue; - if (options.insertSpaces) { - indentValue = repeat(' ', options.tabSize || 4); - } - else { - indentValue = '\t'; - } - var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false); - var hasError = false; - function newLineAndIndent() { - return eol + repeat(indentValue, initialIndentLevel + indentLevel); - } - function scanNext() { - var token = scanner.scan(); - lineBreak = false; - while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) { - lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */); - token = scanner.scan(); - } - hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */; - return token; - } - var editOperations = []; - function addEdit(text, startOffset, endOffset) { - if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) { - editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); - } - } - var firstToken = scanNext(); - if (firstToken !== 17 /* EOF */) { - var firstTokenStart = scanner.getTokenOffset() + formatTextStart; - var initialIndent = repeat(indentValue, initialIndentLevel); - addEdit(initialIndent, formatTextStart, firstTokenStart); - } - while (firstToken !== 17 /* EOF */) { - var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; - var secondToken = scanNext(); - var replaceContent = ''; - while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) { - // comments on the same line: keep them on the same line, but ignore them otherwise - var commentTokenStart = scanner.getTokenOffset() + formatTextStart; - addEdit(' ', firstTokenEnd, commentTokenStart); - firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; - replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : ''; - secondToken = scanNext(); - } - if (secondToken === 2 /* CloseBraceToken */) { - if (firstToken !== 1 /* OpenBraceToken */) { - indentLevel--; - replaceContent = newLineAndIndent(); - } - } - else if (secondToken === 4 /* CloseBracketToken */) { - if (firstToken !== 3 /* OpenBracketToken */) { - indentLevel--; - replaceContent = newLineAndIndent(); - } - } - else { - switch (firstToken) { - case 3 /* OpenBracketToken */: - case 1 /* OpenBraceToken */: - indentLevel++; - replaceContent = newLineAndIndent(); - break; - case 5 /* CommaToken */: - case 12 /* LineCommentTrivia */: - replaceContent = newLineAndIndent(); - break; - case 13 /* BlockCommentTrivia */: - if (lineBreak) { - replaceContent = newLineAndIndent(); - } - else { - // symbol following comment on the same line: keep on same line, separate with ' ' - replaceContent = ' '; - } - break; - case 6 /* ColonToken */: - replaceContent = ' '; - break; - case 10 /* StringLiteral */: - if (secondToken === 6 /* ColonToken */) { - replaceContent = ''; - break; - } - // fall through - case 7 /* NullKeyword */: - case 8 /* TrueKeyword */: - case 9 /* FalseKeyword */: - case 11 /* NumericLiteral */: - case 2 /* CloseBraceToken */: - case 4 /* CloseBracketToken */: - if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) { - replaceContent = ' '; - } - else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) { - hasError = true; - } - break; - case 16 /* Unknown */: - hasError = true; - break; - } - if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) { - replaceContent = newLineAndIndent(); - } - } - var secondTokenStart = scanner.getTokenOffset() + formatTextStart; - addEdit(replaceContent, firstTokenEnd, secondTokenStart); - firstToken = secondToken; - } - return editOperations; -} -function repeat(s, count) { - var result = ''; - for (var i = 0; i < count; i++) { - result += s; - } - return result; -} -function computeIndentLevel(content, options) { - var i = 0; - var nChars = 0; - var tabSize = options.tabSize || 4; - while (i < content.length) { - var ch = content.charAt(i); - if (ch === ' ') { - nChars++; - } - else if (ch === '\t') { - nChars += tabSize; - } - else { - break; - } - i++; - } - return Math.floor(nChars / tabSize); -} -function getEOL(options, text) { - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch === '\r') { - if (i + 1 < text.length && text.charAt(i + 1) === '\n') { - return '\r\n'; - } - return '\r'; - } - else if (ch === '\n') { - return '\n'; - } - } - return (options && options.eol) || '\n'; -} -function isEOL(text, offset) { - return '\r\n'.indexOf(text.charAt(offset)) !== -1; -} - - -/***/ }), -/* 303 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; }); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -/** - * Creates a JSON scanner on the given text. - * If ignoreTrivia is set, whitespaces or comments are ignored. - */ -function createScanner(text, ignoreTrivia) { - if (ignoreTrivia === void 0) { ignoreTrivia = false; } - var len = text.length; - var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */; - function scanHexDigits(count, exact) { - var digits = 0; - var value = 0; - while (digits < count || !exact) { - var ch = text.charCodeAt(pos); - if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { - value = value * 16 + ch - 48 /* _0 */; - } - else if (ch >= 65 /* A */ && ch <= 70 /* F */) { - value = value * 16 + ch - 65 /* A */ + 10; - } - else if (ch >= 97 /* a */ && ch <= 102 /* f */) { - value = value * 16 + ch - 97 /* a */ + 10; - } - else { - break; - } - pos++; - digits++; - } - if (digits < count) { - value = -1; - } - return value; - } - function setPosition(newPosition) { - pos = newPosition; - value = ''; - tokenOffset = 0; - token = 16 /* Unknown */; - scanError = 0 /* None */; - } - function scanNumber() { - var start = pos; - if (text.charCodeAt(pos) === 48 /* _0 */) { - pos++; - } - else { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - } - if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) { - pos++; - if (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - } - else { - scanError = 3 /* UnexpectedEndOfNumber */; - return text.substring(start, pos); - } - } - var end = pos; - if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) { - pos++; - if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) { - pos++; - } - if (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - end = pos; - } - else { - scanError = 3 /* UnexpectedEndOfNumber */; - } - } - return text.substring(start, end); - } - function scanString() { - var result = '', start = pos; - while (true) { - if (pos >= len) { - result += text.substring(start, pos); - scanError = 2 /* UnexpectedEndOfString */; - break; - } - var ch = text.charCodeAt(pos); - if (ch === 34 /* doubleQuote */) { - result += text.substring(start, pos); - pos++; - break; - } - if (ch === 92 /* backslash */) { - result += text.substring(start, pos); - pos++; - if (pos >= len) { - scanError = 2 /* UnexpectedEndOfString */; - break; - } - var ch2 = text.charCodeAt(pos++); - switch (ch2) { - case 34 /* doubleQuote */: - result += '\"'; - break; - case 92 /* backslash */: - result += '\\'; - break; - case 47 /* slash */: - result += '/'; - break; - case 98 /* b */: - result += '\b'; - break; - case 102 /* f */: - result += '\f'; - break; - case 110 /* n */: - result += '\n'; - break; - case 114 /* r */: - result += '\r'; - break; - case 116 /* t */: - result += '\t'; - break; - case 117 /* u */: - var ch3 = scanHexDigits(4, true); - if (ch3 >= 0) { - result += String.fromCharCode(ch3); - } - else { - scanError = 4 /* InvalidUnicode */; - } - break; - default: - scanError = 5 /* InvalidEscapeCharacter */; - } - start = pos; - continue; - } - if (ch >= 0 && ch <= 0x1f) { - if (isLineBreak(ch)) { - result += text.substring(start, pos); - scanError = 2 /* UnexpectedEndOfString */; - break; - } - else { - scanError = 6 /* InvalidCharacter */; - // mark as error but continue with string - } - } - pos++; - } - return result; - } - function scanNext() { - value = ''; - scanError = 0 /* None */; - tokenOffset = pos; - lineStartOffset = lineNumber; - prevTokenLineStartOffset = tokenLineStartOffset; - if (pos >= len) { - // at the end - tokenOffset = len; - return token = 17 /* EOF */; - } - var code = text.charCodeAt(pos); - // trivia: whitespace - if (isWhiteSpace(code)) { - do { - pos++; - value += String.fromCharCode(code); - code = text.charCodeAt(pos); - } while (isWhiteSpace(code)); - return token = 15 /* Trivia */; - } - // trivia: newlines - if (isLineBreak(code)) { - pos++; - value += String.fromCharCode(code); - if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) { - pos++; - value += '\n'; - } - lineNumber++; - tokenLineStartOffset = pos; - return token = 14 /* LineBreakTrivia */; - } - switch (code) { - // tokens: []{}:, - case 123 /* openBrace */: - pos++; - return token = 1 /* OpenBraceToken */; - case 125 /* closeBrace */: - pos++; - return token = 2 /* CloseBraceToken */; - case 91 /* openBracket */: - pos++; - return token = 3 /* OpenBracketToken */; - case 93 /* closeBracket */: - pos++; - return token = 4 /* CloseBracketToken */; - case 58 /* colon */: - pos++; - return token = 6 /* ColonToken */; - case 44 /* comma */: - pos++; - return token = 5 /* CommaToken */; - // strings - case 34 /* doubleQuote */: - pos++; - value = scanString(); - return token = 10 /* StringLiteral */; - // comments - case 47 /* slash */: - var start = pos - 1; - // Single-line comment - if (text.charCodeAt(pos + 1) === 47 /* slash */) { - pos += 2; - while (pos < len) { - if (isLineBreak(text.charCodeAt(pos))) { - break; - } - pos++; - } - value = text.substring(start, pos); - return token = 12 /* LineCommentTrivia */; - } - // Multi-line comment - if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { - pos += 2; - var safeLength = len - 1; // For lookahead. - var commentClosed = false; - while (pos < safeLength) { - var ch = text.charCodeAt(pos); - if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { - pos += 2; - commentClosed = true; - break; - } - pos++; - if (isLineBreak(ch)) { - if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) { - pos++; - } - lineNumber++; - tokenLineStartOffset = pos; - } - } - if (!commentClosed) { - pos++; - scanError = 1 /* UnexpectedEndOfComment */; - } - value = text.substring(start, pos); - return token = 13 /* BlockCommentTrivia */; - } - // just a single slash - value += String.fromCharCode(code); - pos++; - return token = 16 /* Unknown */; - // numbers - case 45 /* minus */: - value += String.fromCharCode(code); - pos++; - if (pos === len || !isDigit(text.charCodeAt(pos))) { - return token = 16 /* Unknown */; - } - // found a minus, followed by a number so - // we fall through to proceed with scanning - // numbers - case 48 /* _0 */: - case 49 /* _1 */: - case 50 /* _2 */: - case 51 /* _3 */: - case 52 /* _4 */: - case 53 /* _5 */: - case 54 /* _6 */: - case 55 /* _7 */: - case 56 /* _8 */: - case 57 /* _9 */: - value += scanNumber(); - return token = 11 /* NumericLiteral */; - // literals and unknown symbols - default: - // is a literal? Read the full word. - while (pos < len && isUnknownContentCharacter(code)) { - pos++; - code = text.charCodeAt(pos); - } - if (tokenOffset !== pos) { - value = text.substring(tokenOffset, pos); - // keywords: true, false, null - switch (value) { - case 'true': return token = 8 /* TrueKeyword */; - case 'false': return token = 9 /* FalseKeyword */; - case 'null': return token = 7 /* NullKeyword */; - } - return token = 16 /* Unknown */; - } - // some - value += String.fromCharCode(code); - pos++; - return token = 16 /* Unknown */; - } - } - function isUnknownContentCharacter(code) { - if (isWhiteSpace(code) || isLineBreak(code)) { - return false; - } - switch (code) { - case 125 /* closeBrace */: - case 93 /* closeBracket */: - case 123 /* openBrace */: - case 91 /* openBracket */: - case 34 /* doubleQuote */: - case 58 /* colon */: - case 44 /* comma */: - case 47 /* slash */: - return false; - } - return true; - } - function scanNextNonTrivia() { - var result; - do { - result = scanNext(); - } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */); - return result; - } - return { - setPosition: setPosition, - getPosition: function () { return pos; }, - scan: ignoreTrivia ? scanNextNonTrivia : scanNext, - getToken: function () { return token; }, - getTokenValue: function () { return value; }, - getTokenOffset: function () { return tokenOffset; }, - getTokenLength: function () { return pos - tokenOffset; }, - getTokenStartLine: function () { return lineStartOffset; }, - getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; }, - getTokenError: function () { return scanError; }, - }; -} -function isWhiteSpace(ch) { - return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || - ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || - ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; -} -function isLineBreak(ch) { - return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */; -} -function isDigit(ch) { - return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; -} - - -/***/ }), -/* 304 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; }); -/* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(302); -/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(305); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - -function removeProperty(text, path, options) { - return setProperty(text, path, void 0, options); -} -function setProperty(text, originalPath, value, options) { - var _a; - var path = originalPath.slice(); - var errors = []; - var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors); - var parent = void 0; - var lastSegment = void 0; - while (path.length > 0) { - lastSegment = path.pop(); - parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path); - if (parent === void 0 && value !== void 0) { - if (typeof lastSegment === 'string') { - value = (_a = {}, _a[lastSegment] = value, _a); - } - else { - value = [value]; - } - } - else { - break; - } - } - if (!parent) { - // empty document - if (value === void 0) { // delete - throw new Error('Can not delete in empty document'); - } - return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); - } - else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { - var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]); - if (existing !== void 0) { - if (value === void 0) { // delete - if (!existing.parent) { - throw new Error('Malformed AST'); - } - var propertyIndex = parent.children.indexOf(existing.parent); - var removeBegin = void 0; - var removeEnd = existing.parent.offset + existing.parent.length; - if (propertyIndex > 0) { - // remove the comma of the previous node - var previous = parent.children[propertyIndex - 1]; - removeBegin = previous.offset + previous.length; - } - else { - removeBegin = parent.offset + 1; - if (parent.children.length > 1) { - // remove the comma of the next node - var next = parent.children[1]; - removeEnd = next.offset; - } - } - return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); - } - else { - // set value of existing property - return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); - } - } - else { - if (value === void 0) { // delete - return []; // property does not exist, nothing to do - } - var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value); - var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length; - var edit = void 0; - if (index > 0) { - var previous = parent.children[index - 1]; - edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; - } - else if (parent.children.length === 0) { - edit = { offset: parent.offset + 1, length: 0, content: newProperty }; - } - else { - edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; - } - return withFormatting(text, edit, options); - } - } - else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { - var insertIndex = lastSegment; - if (insertIndex === -1) { - // Insert - var newProperty = "" + JSON.stringify(value); - var edit = void 0; - if (parent.children.length === 0) { - edit = { offset: parent.offset + 1, length: 0, content: newProperty }; - } - else { - var previous = parent.children[parent.children.length - 1]; - edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; - } - return withFormatting(text, edit, options); - } - else if (value === void 0 && parent.children.length >= 0) { - // Removal - var removalIndex = lastSegment; - var toRemove = parent.children[removalIndex]; - var edit = void 0; - if (parent.children.length === 1) { - // only item - edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; - } - else if (parent.children.length - 1 === removalIndex) { - // last item - var previous = parent.children[removalIndex - 1]; - var offset = previous.offset + previous.length; - var parentEndOffset = parent.offset + parent.length; - edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' }; - } - else { - edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; - } - return withFormatting(text, edit, options); - } - else if (value !== void 0) { - var edit = void 0; - var newProperty = "" + JSON.stringify(value); - if (!options.isArrayInsertion && parent.children.length > lastSegment) { - var toModify = parent.children[lastSegment]; - edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; - } - else if (parent.children.length === 0 || lastSegment === 0) { - edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; - } - else { - var index = lastSegment > parent.children.length ? parent.children.length : lastSegment; - var previous = parent.children[index - 1]; - edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; - } - return withFormatting(text, edit, options); - } - else { - throw new Error("Can not " + (value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')) + " Array index " + insertIndex + " as length is not sufficient"); - } - } - else { - throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type); - } -} -function withFormatting(text, edit, options) { - if (!options.formattingOptions) { - return [edit]; - } - // apply the edit - var newText = applyEdit(text, edit); - // format the new text - var begin = edit.offset; - var end = edit.offset + edit.content.length; - if (edit.length === 0 || edit.content.length === 0) { // insert or remove - while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) { - begin--; - } - while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) { - end++; - } - } - var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, options.formattingOptions); - // apply the formatting edits and track the begin and end offsets of the changes - for (var i = edits.length - 1; i >= 0; i--) { - var edit_1 = edits[i]; - newText = applyEdit(newText, edit_1); - begin = Math.min(begin, edit_1.offset); - end = Math.max(end, edit_1.offset + edit_1.length); - end += edit_1.content.length - edit_1.length; - } - // create a single edit with all changes - var editLength = text.length - (newText.length - end) - begin; - return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; -} -function applyEdit(text, edit) { - return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); -} -function isWS(text, offset) { - return '\r\n \t'.indexOf(text.charAt(offset)) !== -1; -} - - -/***/ }), -/* 305 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeType", function() { return getNodeType; }); -/* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(303); -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - -var ParseOptions; -(function (ParseOptions) { - ParseOptions.DEFAULT = { - allowTrailingComma: false - }; -})(ParseOptions || (ParseOptions = {})); -/** - * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. - */ -function getLocation(text, position) { - var segments = []; // strings or numbers - var earlyReturnException = new Object(); - var previousNode = undefined; - var previousNodeInst = { - value: {}, - offset: 0, - length: 0, - type: 'object', - parent: undefined - }; - var isAtPropertyKey = false; - function setPreviousNode(value, offset, length, type) { - previousNodeInst.value = value; - previousNodeInst.offset = offset; - previousNodeInst.length = length; - previousNodeInst.type = type; - previousNodeInst.colonOffset = undefined; - previousNode = previousNodeInst; - } - try { - visit(text, { - onObjectBegin: function (offset, length) { - if (position <= offset) { - throw earlyReturnException; - } - previousNode = undefined; - isAtPropertyKey = position > offset; - segments.push(''); // push a placeholder (will be replaced) - }, - onObjectProperty: function (name, offset, length) { - if (position < offset) { - throw earlyReturnException; - } - setPreviousNode(name, offset, length, 'property'); - segments[segments.length - 1] = name; - if (position <= offset + length) { - throw earlyReturnException; - } - }, - onObjectEnd: function (offset, length) { - if (position <= offset) { - throw earlyReturnException; - } - previousNode = undefined; - segments.pop(); - }, - onArrayBegin: function (offset, length) { - if (position <= offset) { - throw earlyReturnException; - } - previousNode = undefined; - segments.push(0); - }, - onArrayEnd: function (offset, length) { - if (position <= offset) { - throw earlyReturnException; - } - previousNode = undefined; - segments.pop(); - }, - onLiteralValue: function (value, offset, length) { - if (position < offset) { - throw earlyReturnException; - } - setPreviousNode(value, offset, length, getNodeType(value)); - if (position <= offset + length) { - throw earlyReturnException; - } - }, - onSeparator: function (sep, offset, length) { - if (position <= offset) { - throw earlyReturnException; - } - if (sep === ':' && previousNode && previousNode.type === 'property') { - previousNode.colonOffset = offset; - isAtPropertyKey = false; - previousNode = undefined; - } - else if (sep === ',') { - var last = segments[segments.length - 1]; - if (typeof last === 'number') { - segments[segments.length - 1] = last + 1; - } - else { - isAtPropertyKey = true; - segments[segments.length - 1] = ''; - } - previousNode = undefined; - } - } - }); - } - catch (e) { - if (e !== earlyReturnException) { - throw e; - } - } - return { - path: segments, - previousNode: previousNode, - isAtPropertyKey: isAtPropertyKey, - matches: function (pattern) { - var k = 0; - for (var i = 0; k < pattern.length && i < segments.length; i++) { - if (pattern[k] === segments[i] || pattern[k] === '*') { - k++; - } - else if (pattern[k] !== '**') { - return false; - } - } - return k === pattern.length; - } - }; -} -/** - * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. - * Therefore always check the errors list to find out if the input was valid. - */ -function parse(text, errors, options) { - if (errors === void 0) { errors = []; } - if (options === void 0) { options = ParseOptions.DEFAULT; } - var currentProperty = null; - var currentParent = []; - var previousParents = []; - function onValue(value) { - if (Array.isArray(currentParent)) { - currentParent.push(value); - } - else if (currentProperty !== null) { - currentParent[currentProperty] = value; - } - } - var visitor = { - onObjectBegin: function () { - var object = {}; - onValue(object); - previousParents.push(currentParent); - currentParent = object; - currentProperty = null; - }, - onObjectProperty: function (name) { - currentProperty = name; - }, - onObjectEnd: function () { - currentParent = previousParents.pop(); - }, - onArrayBegin: function () { - var array = []; - onValue(array); - previousParents.push(currentParent); - currentParent = array; - currentProperty = null; - }, - onArrayEnd: function () { - currentParent = previousParents.pop(); - }, - onLiteralValue: onValue, - onError: function (error, offset, length) { - errors.push({ error: error, offset: offset, length: length }); - } - }; - visit(text, visitor, options); - return currentParent[0]; -} -/** - * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. - */ -function parseTree(text, errors, options) { - if (errors === void 0) { errors = []; } - if (options === void 0) { options = ParseOptions.DEFAULT; } - var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root - function ensurePropertyComplete(endOffset) { - if (currentParent.type === 'property') { - currentParent.length = endOffset - currentParent.offset; - currentParent = currentParent.parent; - } - } - function onValue(valueNode) { - currentParent.children.push(valueNode); - return valueNode; - } - var visitor = { - onObjectBegin: function (offset) { - currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] }); - }, - onObjectProperty: function (name, offset, length) { - currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] }); - currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent }); - }, - onObjectEnd: function (offset, length) { - ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete - currentParent.length = offset + length - currentParent.offset; - currentParent = currentParent.parent; - ensurePropertyComplete(offset + length); - }, - onArrayBegin: function (offset, length) { - currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] }); - }, - onArrayEnd: function (offset, length) { - currentParent.length = offset + length - currentParent.offset; - currentParent = currentParent.parent; - ensurePropertyComplete(offset + length); - }, - onLiteralValue: function (value, offset, length) { - onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value }); - ensurePropertyComplete(offset + length); - }, - onSeparator: function (sep, offset, length) { - if (currentParent.type === 'property') { - if (sep === ':') { - currentParent.colonOffset = offset; - } - else if (sep === ',') { - ensurePropertyComplete(offset); - } - } - }, - onError: function (error, offset, length) { - errors.push({ error: error, offset: offset, length: length }); - } - }; - visit(text, visitor, options); - var result = currentParent.children[0]; - if (result) { - delete result.parent; - } - return result; -} -/** - * Finds the node at the given path in a JSON DOM. - */ -function findNodeAtLocation(root, path) { - if (!root) { - return undefined; - } - var node = root; - for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { - var segment = path_1[_i]; - if (typeof segment === 'string') { - if (node.type !== 'object' || !Array.isArray(node.children)) { - return undefined; - } - var found = false; - for (var _a = 0, _b = node.children; _a < _b.length; _a++) { - var propertyNode = _b[_a]; - if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) { - node = propertyNode.children[1]; - found = true; - break; - } - } - if (!found) { - return undefined; - } - } - else { - var index = segment; - if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { - return undefined; - } - node = node.children[index]; - } - } - return node; -} -/** - * Gets the JSON path of the given JSON DOM node - */ -function getNodePath(node) { - if (!node.parent || !node.parent.children) { - return []; - } - var path = getNodePath(node.parent); - if (node.parent.type === 'property') { - var key = node.parent.children[0].value; - path.push(key); - } - else if (node.parent.type === 'array') { - var index = node.parent.children.indexOf(node); - if (index !== -1) { - path.push(index); - } - } - return path; -} -/** - * Evaluates the JavaScript object of the given JSON DOM node - */ -function getNodeValue(node) { - switch (node.type) { - case 'array': - return node.children.map(getNodeValue); - case 'object': - var obj = Object.create(null); - for (var _i = 0, _a = node.children; _i < _a.length; _i++) { - var prop = _a[_i]; - var valueNode = prop.children[1]; - if (valueNode) { - obj[prop.children[0].value] = getNodeValue(valueNode); - } - } - return obj; - case 'null': - case 'string': - case 'number': - case 'boolean': - return node.value; - default: - return undefined; - } -} -function contains(node, offset, includeRightBound) { - if (includeRightBound === void 0) { includeRightBound = false; } - return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); -} -/** - * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. - */ -function findNodeAtOffset(node, offset, includeRightBound) { - if (includeRightBound === void 0) { includeRightBound = false; } - if (contains(node, offset, includeRightBound)) { - var children = node.children; - if (Array.isArray(children)) { - for (var i = 0; i < children.length && children[i].offset <= offset; i++) { - var item = findNodeAtOffset(children[i], offset, includeRightBound); - if (item) { - return item; - } - } - } - return node; - } - return undefined; -} -/** - * Parses the given text and invokes the visitor functions for each object, array and literal reached. - */ -function visit(text, visitor, options) { - if (options === void 0) { options = ParseOptions.DEFAULT; } - var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false); - function toNoArgVisit(visitFunction) { - return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; }; - } - function toOneArgVisit(visitFunction) { - return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; }; - } - var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); - var disallowComments = options && options.disallowComments; - var allowTrailingComma = options && options.allowTrailingComma; - function scanNext() { - while (true) { - var token = _scanner.scan(); - switch (_scanner.getTokenError()) { - case 4 /* InvalidUnicode */: - handleError(14 /* InvalidUnicode */); - break; - case 5 /* InvalidEscapeCharacter */: - handleError(15 /* InvalidEscapeCharacter */); - break; - case 3 /* UnexpectedEndOfNumber */: - handleError(13 /* UnexpectedEndOfNumber */); - break; - case 1 /* UnexpectedEndOfComment */: - if (!disallowComments) { - handleError(11 /* UnexpectedEndOfComment */); - } - break; - case 2 /* UnexpectedEndOfString */: - handleError(12 /* UnexpectedEndOfString */); - break; - case 6 /* InvalidCharacter */: - handleError(16 /* InvalidCharacter */); - break; - } - switch (token) { - case 12 /* LineCommentTrivia */: - case 13 /* BlockCommentTrivia */: - if (disallowComments) { - handleError(10 /* InvalidCommentToken */); - } - else { - onComment(); - } - break; - case 16 /* Unknown */: - handleError(1 /* InvalidSymbol */); - break; - case 15 /* Trivia */: - case 14 /* LineBreakTrivia */: - break; - default: - return token; - } - } - } - function handleError(error, skipUntilAfter, skipUntil) { - if (skipUntilAfter === void 0) { skipUntilAfter = []; } - if (skipUntil === void 0) { skipUntil = []; } - onError(error); - if (skipUntilAfter.length + skipUntil.length > 0) { - var token = _scanner.getToken(); - while (token !== 17 /* EOF */) { - if (skipUntilAfter.indexOf(token) !== -1) { - scanNext(); - break; - } - else if (skipUntil.indexOf(token) !== -1) { - break; - } - token = scanNext(); - } - } - } - function parseString(isValue) { - var value = _scanner.getTokenValue(); - if (isValue) { - onLiteralValue(value); - } - else { - onObjectProperty(value); - } - scanNext(); - return true; - } - function parseLiteral() { - switch (_scanner.getToken()) { - case 11 /* NumericLiteral */: - var tokenValue = _scanner.getTokenValue(); - var value = Number(tokenValue); - if (isNaN(value)) { - handleError(2 /* InvalidNumberFormat */); - value = 0; - } - onLiteralValue(value); - break; - case 7 /* NullKeyword */: - onLiteralValue(null); - break; - case 8 /* TrueKeyword */: - onLiteralValue(true); - break; - case 9 /* FalseKeyword */: - onLiteralValue(false); - break; - default: - return false; - } - scanNext(); - return true; - } - function parseProperty() { - if (_scanner.getToken() !== 10 /* StringLiteral */) { - handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); - return false; - } - parseString(false); - if (_scanner.getToken() === 6 /* ColonToken */) { - onSeparator(':'); - scanNext(); // consume colon - if (!parseValue()) { - handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); - } - } - else { - handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); - } - return true; - } - function parseObject() { - onObjectBegin(); - scanNext(); // consume open brace - var needsComma = false; - while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) { - if (_scanner.getToken() === 5 /* CommaToken */) { - if (!needsComma) { - handleError(4 /* ValueExpected */, [], []); - } - onSeparator(','); - scanNext(); // consume comma - if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) { - break; - } - } - else if (needsComma) { - handleError(6 /* CommaExpected */, [], []); - } - if (!parseProperty()) { - handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); - } - needsComma = true; - } - onObjectEnd(); - if (_scanner.getToken() !== 2 /* CloseBraceToken */) { - handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []); - } - else { - scanNext(); // consume close brace - } - return true; - } - function parseArray() { - onArrayBegin(); - scanNext(); // consume open bracket - var needsComma = false; - while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) { - if (_scanner.getToken() === 5 /* CommaToken */) { - if (!needsComma) { - handleError(4 /* ValueExpected */, [], []); - } - onSeparator(','); - scanNext(); // consume comma - if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) { - break; - } - } - else if (needsComma) { - handleError(6 /* CommaExpected */, [], []); - } - if (!parseValue()) { - handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]); - } - needsComma = true; - } - onArrayEnd(); - if (_scanner.getToken() !== 4 /* CloseBracketToken */) { - handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []); - } - else { - scanNext(); // consume close bracket - } - return true; - } - function parseValue() { - switch (_scanner.getToken()) { - case 3 /* OpenBracketToken */: - return parseArray(); - case 1 /* OpenBraceToken */: - return parseObject(); - case 10 /* StringLiteral */: - return parseString(true); - default: - return parseLiteral(); - } - } - scanNext(); - if (_scanner.getToken() === 17 /* EOF */) { - if (options.allowEmptyContent) { - return true; - } - handleError(4 /* ValueExpected */, [], []); - return false; - } - if (!parseValue()) { - handleError(4 /* ValueExpected */, [], []); - return false; - } - if (_scanner.getToken() !== 17 /* EOF */) { - handleError(9 /* EndOfFileExpected */, [], []); - } - return true; -} -/** - * Takes JSON with JavaScript-style comments and remove - * them. Optionally replaces every none-newline character - * of comments with a replaceCharacter - */ -function stripComments(text, replaceCh) { - var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos; - do { - pos = _scanner.getPosition(); - kind = _scanner.scan(); - switch (kind) { - case 12 /* LineCommentTrivia */: - case 13 /* BlockCommentTrivia */: - case 17 /* EOF */: - if (offset !== pos) { - parts.push(text.substring(offset, pos)); - } - if (replaceCh !== undefined) { - parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); - } - offset = _scanner.getPosition(); - break; - } - } while (kind !== 17 /* EOF */); - return parts.join(''); -} -function getNodeType(value) { - switch (typeof value) { - case 'boolean': return 'boolean'; - case 'number': return 'number'; - case 'string': return 'string'; - case 'object': { - if (!value) { - return 'null'; - } - else if (Array.isArray(value)) { - return 'array'; - } - return 'object'; - } - default: return 'null'; - } -} - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fixDriver = exports.isParentFolder = exports.parentDirs = exports.realpathAsync = exports.readdirAsync = exports.isFile = exports.validSocket = exports.writeFile = exports.readFileLine = exports.readFileLines = exports.getFileLineCount = exports.readFile = exports.findUp = exports.inDirectory = exports.resolveRoot = exports.isGitIgnored = exports.renameAsync = exports.unlinkAsync = exports.isDirectory = exports.statAsync = void 0; -const tslib_1 = __webpack_require__(65); -const child_process_1 = __webpack_require__(239); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const net_1 = tslib_1.__importDefault(__webpack_require__(157)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const readline_1 = tslib_1.__importDefault(__webpack_require__(206)); -const util_1 = tslib_1.__importDefault(__webpack_require__(74)); -const minimatch_1 = tslib_1.__importDefault(__webpack_require__(283)); -const logger = __webpack_require__(64)('util-fs'); -async function statAsync(filepath) { - let stat = null; - try { - stat = await util_1.default.promisify(fs_1.default.stat)(filepath); - } - catch (e) { } - return stat; -} -exports.statAsync = statAsync; -async function isDirectory(filepath) { - let stat = await statAsync(filepath); - return stat && stat.isDirectory(); -} -exports.isDirectory = isDirectory; -async function unlinkAsync(filepath) { - try { - await util_1.default.promisify(fs_1.default.unlink)(filepath); - } - catch (e) { } -} -exports.unlinkAsync = unlinkAsync; -function renameAsync(oldPath, newPath) { - return new Promise((resolve, reject) => { - fs_1.default.rename(oldPath, newPath, err => { - if (err) - return reject(err); - resolve(); - }); - }); -} -exports.renameAsync = renameAsync; -async function isGitIgnored(fullpath) { - if (!fullpath) - return false; - let stat = await statAsync(fullpath); - if (!stat || !stat.isFile()) - return false; - let root = null; - try { - let { stdout } = await util_1.default.promisify(child_process_1.exec)('git rev-parse --show-toplevel', { cwd: path_1.default.dirname(fullpath) }); - root = stdout.trim(); - } - catch (e) { } - if (!root) - return false; - let file = path_1.default.relative(root, fullpath); - try { - let { stdout } = await util_1.default.promisify(child_process_1.exec)(`git check-ignore ${file}`, { cwd: root }); - return stdout.trim() == file; - } - catch (e) { } - return false; -} -exports.isGitIgnored = isGitIgnored; -function resolveRoot(folder, subs, cwd) { - let home = os_1.default.homedir(); - let dir = fixDriver(folder); - if (isParentFolder(dir, home, true)) - return null; - if (cwd && isParentFolder(cwd, dir, true) && inDirectory(cwd, subs)) - return cwd; - let parts = dir.split(path_1.default.sep); - let curr = [parts.shift()]; - for (let part of parts) { - curr.push(part); - let dir = curr.join(path_1.default.sep); - if (dir != home && inDirectory(dir, subs)) { - return dir; - } - } - return null; -} -exports.resolveRoot = resolveRoot; -function inDirectory(dir, subs) { - try { - let files = fs_1.default.readdirSync(dir); - for (let pattern of subs) { - // note, only '*' expanded - let is_wildcard = (pattern.includes('*')); - let res = is_wildcard ? - (minimatch_1.default.match(files, pattern, { nobrace: true, noext: true, nocomment: true, nonegate: true, dot: true }).length !== 0) : - (files.includes(pattern)); - if (res) - return true; - } - } - catch (e) { - // could be failed without permission - } - return false; -} -exports.inDirectory = inDirectory; -function findUp(name, cwd) { - let root = path_1.default.parse(cwd).root; - let subs = Array.isArray(name) ? name : [name]; - while (cwd && cwd !== root) { - let find = inDirectory(cwd, subs); - if (find) { - for (let sub of subs) { - let filepath = path_1.default.join(cwd, sub); - if (fs_1.default.existsSync(filepath)) { - return filepath; - } - } - } - cwd = path_1.default.dirname(cwd); - } - return null; -} -exports.findUp = findUp; -function readFile(fullpath, encoding) { - return new Promise((resolve, reject) => { - fs_1.default.readFile(fullpath, encoding, (err, content) => { - if (err) - reject(err); - resolve(content); - }); - }); -} -exports.readFile = readFile; -function getFileLineCount(filepath) { - let i; - let count = 0; - return new Promise((resolve, reject) => { - fs_1.default.createReadStream(filepath) - .on('error', e => reject(e)) - .on('data', chunk => { - for (i = 0; i < chunk.length; ++i) - if (chunk[i] == 10) - count++; - }) - .on('end', () => resolve(count)); - }); -} -exports.getFileLineCount = getFileLineCount; -function readFileLines(fullpath, start, end) { - if (!fs_1.default.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)); - } - let res = []; - const rl = readline_1.default.createInterface({ - input: fs_1.default.createReadStream(fullpath, { encoding: 'utf8' }), - crlfDelay: Infinity, - terminal: false - }); - let n = 0; - return new Promise((resolve, reject) => { - rl.on('line', line => { - if (n == 0 && line.startsWith('\uFEFF')) { - // handle BOM - line = line.slice(1); - } - if (n >= start && n <= end) { - res.push(line); - } - if (n == end) { - rl.close(); - } - n = n + 1; - }); - rl.on('close', () => { - resolve(res); - }); - rl.on('error', reject); - }); -} -exports.readFileLines = readFileLines; -function readFileLine(fullpath, count) { - if (!fs_1.default.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)); - } - const rl = readline_1.default.createInterface({ - input: fs_1.default.createReadStream(fullpath, { encoding: 'utf8' }), - crlfDelay: Infinity, - terminal: false - }); - let n = 0; - return new Promise((resolve, reject) => { - rl.on('line', line => { - if (n == count) { - if (n == 0 && line.startsWith('\uFEFF')) { - // handle BOM - line = line.slice(1); - } - rl.close(); - resolve(line); - return; - } - n = n + 1; - }); - rl.on('error', reject); - }); -} -exports.readFileLine = readFileLine; -async function writeFile(fullpath, content) { - await util_1.default.promisify(fs_1.default.writeFile)(fullpath, content, { encoding: 'utf8' }); -} -exports.writeFile = writeFile; -function validSocket(path) { - let clientSocket = new net_1.default.Socket(); - return new Promise(resolve => { - clientSocket.on('error', () => { - resolve(false); - }); - clientSocket.connect({ path }, () => { - clientSocket.unref(); - resolve(true); - }); - }); -} -exports.validSocket = validSocket; -function isFile(uri) { - return uri.startsWith('file:'); -} -exports.isFile = isFile; -exports.readdirAsync = util_1.default.promisify(fs_1.default.readdir); -exports.realpathAsync = util_1.default.promisify(fs_1.default.realpath); -function parentDirs(pth) { - let { root, dir } = path_1.default.parse(pth); - if (dir === root) - return [root]; - const dirs = [root]; - const parts = dir.slice(root.length).split(path_1.default.sep); - for (let i = 1; i <= parts.length; i++) { - dirs.push(path_1.default.join(root, parts.slice(0, i).join(path_1.default.sep))); - } - return dirs; -} -exports.parentDirs = parentDirs; -function isParentFolder(folder, filepath, checkEqual = false) { - let pdir = fixDriver(path_1.default.resolve(path_1.default.normalize(folder))); - let dir = fixDriver(path_1.default.resolve(path_1.default.normalize(filepath))); - if (pdir == '//') - pdir = '/'; - if (pdir == dir) - return checkEqual ? true : false; - if (pdir.endsWith(path_1.default.sep)) - return dir.startsWith(pdir); - return dir.startsWith(pdir) && dir[pdir.length] == path_1.default.sep; -} -exports.isParentFolder = isParentFolder; -// use uppercase for windows driver -function fixDriver(filepath) { - if (os_1.default.platform() != 'win32' || filepath[1] != ':') - return filepath; - return filepath[0].toUpperCase() + filepath.slice(1); -} -exports.fixDriver = fixDriver; -//# sourceMappingURL=fs.js.map - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const jsonc_parser_1 = __webpack_require__(301); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const vscode_uri_1 = __webpack_require__(243); -const util_1 = __webpack_require__(238); -const logger = __webpack_require__(64)('configuration-shape'); -class ConfigurationProxy { - constructor(workspace) { - this.workspace = workspace; - } - get nvim() { - return this.workspace.nvim; - } - async modifyConfiguration(target, key, value) { - let { nvim, workspace } = this; - let file = workspace.getConfigFile(target); - if (!file) - return; - let formattingOptions = { tabSize: 2, insertSpaces: true }; - let content = fs_1.default.readFileSync(file, 'utf8'); - value = value == null ? undefined : value; - let edits = jsonc_parser_1.modify(content, [key], value, { formattingOptions }); - content = jsonc_parser_1.applyEdits(content, edits); - fs_1.default.writeFileSync(file, content, 'utf8'); - let doc = workspace.getDocument(vscode_uri_1.URI.file(file).toString()); - if (doc) - nvim.command('checktime', true); - return; - } - get workspaceConfigFile() { - let folder = path_1.default.join(this.workspace.root, '.vim'); - return path_1.default.join(folder, util_1.CONFIG_FILE_NAME); - } - $updateConfigurationOption(target, key, value) { - this.modifyConfiguration(target, key, value).logError(); - } - $removeConfigurationOption(target, key) { - this.modifyConfiguration(target, key).logError(); - } -} -exports.default = ConfigurationProxy; -//# sourceMappingURL=shape.js.map - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Channels = void 0; -const tslib_1 = __webpack_require__(65); -const outputChannel_1 = tslib_1.__importDefault(__webpack_require__(309)); -const outputChannels = new Map(); -class Channels { - get names() { - return Array.from(outputChannels.keys()); - } - get(channelName) { - return outputChannels.get(channelName); - } - create(name, nvim) { - if (outputChannels.has(name)) - return outputChannels.get(name); - let channel = new outputChannel_1.default(name, nvim); - outputChannels.set(name, channel); - return channel; - } - show(name, preserveFocus) { - let channel = outputChannels.get(name); - if (!channel) - return; - channel.show(preserveFocus); - } - dispose() { - for (let channel of outputChannels.values()) { - channel.dispose(); - } - outputChannels.clear(); - } -} -exports.Channels = Channels; -exports.default = new Channels(); -//# sourceMappingURL=channels.js.map - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const util_1 = __webpack_require__(238); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const logger = __webpack_require__(64)("outpubChannel"); -const MAX_STRING_LENGTH = __webpack_require__(310).constants.MAX_STRING_LENGTH; -class BufferChannel { - constructor(name, nvim) { - this.name = name; - this.nvim = nvim; - this._content = ''; - this.disposables = []; - this._showing = false; - this.promise = Promise.resolve(void 0); - } - get content() { - return this._content; - } - async _append(value, isLine) { - let { buffer } = this; - if (!buffer) - return; - try { - if (isLine) { - await buffer.append(value.split('\n')); - } - else { - let last = await this.nvim.call('getbufline', [buffer.id, '$']); - let content = last + value; - if (this.buffer) { - await buffer.setLines(content.split('\n'), { - start: -2, - end: -1, - strictIndexing: false - }); - } - } - } - catch (e) { - logger.error(`Error on append output:`, e); - } - } - append(value) { - if (this._content.length + value.length >= MAX_STRING_LENGTH) { - this.clear(10); - } - this._content += value; - this.promise = this.promise.then(() => this._append(value, false)); - } - appendLine(value) { - if (this._content.length + value.length >= MAX_STRING_LENGTH) { - this.clear(10); - } - this._content += value + '\n'; - this.promise = this.promise.then(() => this._append(value, true)); - } - clear(keep) { - let latest = []; - if (keep) { - latest = this._content.split('\n').slice(-keep); - } - this._content = latest.join('\n'); - let { buffer } = this; - if (buffer) { - Promise.resolve(buffer.setLines(latest, { - start: 0, - end: -1, - strictIndexing: false - })).catch(_e => { - // noop - }); - } - } - hide() { - let { nvim, buffer } = this; - if (buffer) - nvim.command(`silent! bd! ${buffer.id}`, true); - } - dispose() { - this.hide(); - this._content = ''; - util_1.disposeAll(this.disposables); - } - get buffer() { - let doc = workspace_1.default.getDocument(`output:///${this.name}`); - return doc ? doc.buffer : null; - } - async openBuffer(preserveFocus) { - let { nvim, buffer } = this; - if (buffer) { - let loaded = await nvim.call('bufloaded', buffer.id); - if (!loaded) - buffer = null; - } - if (!buffer) { - await nvim.command(`belowright vs output:///${this.name}`); - } - else { - // check shown - let wnr = await nvim.call('bufwinnr', buffer.id); - if (wnr != -1) - return; - await nvim.command(`vert belowright sb ${buffer.id}`); - } - if (preserveFocus) { - await nvim.command('wincmd p'); - } - } - show(preserveFocus) { - if (this._showing) - return; - this._showing = true; - this.openBuffer(preserveFocus).then(() => { - this._showing = false; - }, () => { - this._showing = false; - }); - } -} -exports.default = BufferChannel; -//# sourceMappingURL=outputChannel.js.map - -/***/ }), -/* 310 */ -/***/ (function(module, exports) { - -module.exports = require("buffer"); - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -class DB { - constructor(filepath) { - this.filepath = filepath; - } - /** - * Get data by key. - * - * @param {string} key unique key allows dot notation. - * @returns {any} - */ - fetch(key) { - let obj = this.load(); - if (!key) - return obj; - let parts = key.split('.'); - for (let part of parts) { - if (typeof obj[part] == 'undefined') { - return undefined; - } - obj = obj[part]; - } - return obj; - } - /** - * Check if key exists - * - * @param {string} key unique key allows dot notation. - */ - exists(key) { - let obj = this.load(); - let parts = key.split('.'); - for (let part of parts) { - if (typeof obj[part] == 'undefined') { - return false; - } - obj = obj[part]; - } - return true; - } - /** - * Delete data by key - * - * @param {string} key unique key allows dot notation. - */ - delete(key) { - let obj = this.load(); - let origin = obj; - let parts = key.split('.'); - let len = parts.length; - for (let i = 0; i < len; i++) { - if (typeof obj[parts[i]] == 'undefined') { - break; - } - if (i == len - 1) { - delete obj[parts[i]]; - fs_1.default.writeFileSync(this.filepath, JSON.stringify(origin, null, 2), 'utf8'); - break; - } - obj = obj[parts[i]]; - } - } - /** - * Save data with key - * - * @param {string} key unique string that allows dot notation. - * @param {number|null|boolean|string|{[index} data saved data. - */ - push(key, data) { - let origin = this.load() || {}; - let obj = origin; - let parts = key.split('.'); - let len = parts.length; - if (obj == null) { - let dir = path_1.default.dirname(this.filepath); - mkdirp_1.default.sync(dir); - obj = origin; - } - for (let i = 0; i < len; i++) { - let key = parts[i]; - if (i == len - 1) { - obj[key] = data; - fs_1.default.writeFileSync(this.filepath, JSON.stringify(origin, null, 2)); - break; - } - if (typeof obj[key] == 'undefined') { - obj[key] = {}; - obj = obj[key]; - } - else { - obj = obj[key]; - } - } - } - load() { - let dir = path_1.default.dirname(this.filepath); - let stat = fs_1.default.statSync(dir); - if (!stat || !stat.isDirectory()) { - mkdirp_1.default.sync(dir); - fs_1.default.writeFileSync(this.filepath, '{}', 'utf8'); - return {}; - } - try { - let content = fs_1.default.readFileSync(this.filepath, 'utf8'); - return JSON.parse(content.trim()); - } - catch (e) { - fs_1.default.writeFileSync(this.filepath, '{}', 'utf8'); - return {}; - } - } - /** - * Empty db file. - */ - clear() { - let stat = fs_1.default.statSync(this.filepath); - if (!stat || !stat.isFile()) - return; - fs_1.default.writeFileSync(this.filepath, '{}', 'utf8'); - } - /** - * Remove db file. - */ - destroy() { - if (fs_1.default.existsSync(this.filepath)) { - fs_1.default.unlinkSync(this.filepath); - } - } -} -exports.default = DB; -//# sourceMappingURL=db.js.map - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const debounce_1 = tslib_1.__importDefault(__webpack_require__(240)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_languageserver_textdocument_1 = __webpack_require__(295); -const vscode_uri_1 = __webpack_require__(243); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const array_1 = __webpack_require__(257); -const diff_1 = __webpack_require__(313); -const fs_1 = __webpack_require__(306); -const index_1 = __webpack_require__(238); -const position_1 = __webpack_require__(315); -const string_1 = __webpack_require__(314); -const chars_1 = __webpack_require__(316); -const logger = __webpack_require__(64)('model-document'); -// wrapper class of TextDocument -class Document { - constructor(buffer, env, maxFileSize) { - this.buffer = buffer; - this.env = env; - this.maxFileSize = maxFileSize; - this.isIgnored = false; - // start id for matchaddpos - this.colorId = 1080; - this.size = 0; - this.eol = true; - // real current lines - this.lines = []; - this._attached = false; - this._previewwindow = false; - this._winid = -1; - this._words = []; - this._onDocumentChange = new vscode_languageserver_protocol_1.Emitter(); - this._onDocumentDetach = new vscode_languageserver_protocol_1.Emitter(); - this.disposables = []; - this.onDocumentChange = this._onDocumentChange.event; - this.onDocumentDetach = this._onDocumentDetach.event; - this.fireContentChanges = debounce_1.default(() => { - this._fireContentChanges(); - }, 200); - this.fetchContent = debounce_1.default(() => { - this._fetchContent().logError(); - }, 100); - } - /** - * Check if current document should be attached for changes. - * - * Currently only attach for empty and `acwrite` buftype. - */ - get shouldAttach() { - let { buftype, maxFileSize } = this; - if (!this.getVar('enabled', true)) - return false; - if (this.uri.endsWith('%5BCommand%20Line%5D')) - return true; - // too big - if (this.size == -2) - return false; - if (maxFileSize && this.size > maxFileSize) - return false; - return buftype == '' || buftype == 'acwrite'; - } - get isCommandLine() { - return this.uri && this.uri.endsWith('%5BCommand%20Line%5D'); - } - get enabled() { - return this.getVar('enabled', true); - } - /** - * All words, extracted by `iskeyword` option. - */ - get words() { - return this._words; - } - /** - * Map filetype for languageserver. - */ - convertFiletype(filetype) { - let map = this.env.filetypeMap; - if (filetype == 'javascript.jsx') - return 'javascriptreact'; - if (filetype == 'typescript.jsx' || filetype == 'typescript.tsx') - return 'typescriptreact'; - return map[filetype] || filetype; - } - /** - * Get current buffer changedtick. - */ - get changedtick() { - return this._changedtick; - } - /** - * Scheme of document. - */ - get schema() { - return vscode_uri_1.URI.parse(this.uri).scheme; - } - /** - * Line count of current buffer. - */ - get lineCount() { - return this.lines.length; - } - /** - * Window ID when buffer create, could be -1 when no window associated. - */ - get winid() { - return this._winid; - } - /** - * Returns if current document is opended with previewwindow - */ - get previewwindow() { - return this._previewwindow; - } - /** - * Initialize document model. - * - * @internal - */ - async init(nvim, token) { - this.nvim = nvim; - let { buffer } = this; - let opts = await nvim.call('coc#util#get_bufoptions', buffer.id); - if (opts == null) - return false; - let buftype = this.buftype = opts.buftype; - this._previewwindow = opts.previewwindow; - this._winid = opts.winid; - this.size = typeof opts.size == 'number' ? opts.size : 0; - this.variables = opts.variables; - this._changedtick = opts.changedtick; - this.eol = opts.eol == 1; - let uri = this._uri = index_1.getUri(opts.fullpath, buffer.id, buftype, this.env.isCygwin); - if (token.isCancellationRequested) - return false; - if (this.shouldAttach) { - let res = await this.attach(); - if (!res) - return false; - this._attached = true; - } - this._filetype = this.convertFiletype(opts.filetype); - this.textDocument = vscode_languageserver_textdocument_1.TextDocument.create(uri, this.filetype, 1, this.getDocumentContent()); - this.setIskeyword(opts.iskeyword); - this.gitCheck(); - if (token.isCancellationRequested) { - this.detach(); - return false; - } - return true; - } - async attach() { - if (this.env.isVim) { - this.lines = await this.nvim.call('getbufline', [this.bufnr, 1, '$']); - return true; - } - let attached = await this.buffer.attach(false); - if (!attached) - return false; - this.lines = await this.buffer.lines; - let lastChange; - this.buffer.listen('lines', (...args) => { - // avoid neovim send same change multiple times after checktime - if (lastChange == args[1]) - return; - lastChange = args[1]; - this.onChange.apply(this, args); - }, this.disposables); - this.buffer.listen('detach', async (buf) => { - this._onDocumentDetach.fire(buf.id); - }, this.disposables); - this.buffer.listen('changedtick', (_buf, tick) => { - this._changedtick = tick; - }, this.disposables); - if (this.textDocument) { - this.fireContentChanges(); - } - return true; - } - onChange(buf, tick, firstline, lastline, linedata - // more:boolean - ) { - if (buf.id !== this.buffer.id || tick == null) - return; - this._changedtick = tick; - let lines = this.lines.slice(0, firstline); - lines = lines.concat(linedata, this.lines.slice(lastline)); - this.lines = lines; - this.fireContentChanges(); - } - /** - * Make sure current document synced correctly - */ - async checkDocument() { - let { buffer } = this; - this._changedtick = await buffer.changedtick; - this.lines = await buffer.lines; - this.fireContentChanges.clear(); - this._fireContentChanges(); - } - /** - * Check if document changed after last synchronize - */ - get dirty() { - return this.content != this.getDocumentContent(); - } - _fireContentChanges() { - let { textDocument } = this; - let { cursor } = events_1.default; - try { - let content = this.getDocumentContent(); - let endOffset = null; - if (cursor && cursor.bufnr == this.bufnr) { - endOffset = this.getEndOffset(cursor.lnum, cursor.col, cursor.insert); - } - let change = diff_1.getChange(this.content, content, endOffset); - if (change == null) - return; - this.createDocument(); - let { version, uri } = this; - let start = textDocument.positionAt(change.start); - let end = textDocument.positionAt(change.end); - let original = textDocument.getText(vscode_languageserver_protocol_1.Range.create(start, end)); - let changes = [{ - range: { start, end }, - rangeLength: change.end - change.start, - text: change.newText - }]; - this._onDocumentChange.fire({ - bufnr: this.bufnr, - original, - textDocument: { version, uri }, - contentChanges: changes - }); - this._words = this.chars.matchKeywords(this.textDocument.getText()); - } - catch (e) { - logger.error(e.message); - } - } - /** - * Buffer number - */ - get bufnr() { - return this.buffer.id; - } - /** - * Content of textDocument. - */ - get content() { - return this.textDocument.getText(); - } - /** - * Coverted filetype. - */ - get filetype() { - return this._filetype; - } - get uri() { - return this._uri; - } - get version() { - return this.textDocument ? this.textDocument.version : null; - } - async applyEdits(edits) { - if (!Array.isArray(arguments[0]) && Array.isArray(arguments[1])) { - edits = arguments[1]; - } - if (edits.length == 0) - return; - edits.forEach(edit => { - edit.newText = edit.newText.replace(/\r/g, ''); - }); - let current = this.lines.join('\n') + (this.eol ? '\n' : ''); - let textDocument = vscode_languageserver_textdocument_1.TextDocument.create(this.uri, this.filetype, 1, current); - // apply edits to current textDocument - let applied = vscode_languageserver_textdocument_1.TextDocument.applyEdits(textDocument, edits); - // could be equal sometimes - if (current !== applied) { - let newLines = applied.split('\n'); - if (this.eol && newLines[newLines.length - 1] == '') { - newLines = newLines.slice(0, -1); - } - let d = diff_1.diffLines(this.lines, newLines); - await this.buffer.setLines(d.replacement, { - start: d.start, - end: d.end, - strictIndexing: false - }); - // can't wait vim sync buffer - this.lines = newLines; - this.forceSync(); - } - } - changeLines(lines, sync = true, check = false) { - let { nvim } = this; - let filtered = []; - for (let [lnum, text] of lines) { - if (check && this.lines[lnum] != text) { - filtered.push([lnum, text]); - } - this.lines[lnum] = text; - } - if (check && !filtered.length) - return; - nvim.call('coc#util#change_lines', [this.bufnr, check ? filtered : lines], true); - if (sync) - this.forceSync(); - } - /** - * Force document synchronize and emit change event when necessary. - */ - forceSync() { - this.fireContentChanges.clear(); - this._fireContentChanges(); - } - /** - * Get offset from lnum & col - */ - getOffset(lnum, col) { - return this.textDocument.offsetAt({ - line: lnum - 1, - character: col - }); - } - /** - * Check string is word. - */ - isWord(word) { - return this.chars.isKeyword(word); - } - /** - * Generate more words by split word with `-` - */ - getMoreWords() { - let res = []; - let { words, chars } = this; - if (!chars.isKeywordChar('-')) - return res; - for (let word of words) { - word = word.replace(/^-+/, ''); - if (word.includes('-')) { - let parts = word.split('-'); - for (let part of parts) { - if (part.length > 2 && - !res.includes(part) && - !words.includes(part)) { - res.push(part); - } - } - } - } - return res; - } - /** - * Current word for replacement - */ - getWordRangeAtPosition(position, extraChars, current = true) { - let chars = this.chars.clone(); - if (extraChars && extraChars.length) { - for (let ch of extraChars) { - chars.addKeyword(ch); - } - } - let line = this.getline(position.line, current); - if (line.length == 0 || position.character >= line.length) - return null; - if (!chars.isKeywordChar(line[position.character])) - return null; - let start = position.character; - let end = position.character + 1; - if (!chars.isKeywordChar(line[start])) { - return vscode_languageserver_protocol_1.Range.create(position, { line: position.line, character: position.character + 1 }); - } - while (start >= 0) { - let ch = line[start - 1]; - if (!ch || !chars.isKeyword(ch)) - break; - start = start - 1; - } - while (end <= line.length) { - let ch = line[end]; - if (!ch || !chars.isKeywordChar(ch)) - break; - end = end + 1; - } - return vscode_languageserver_protocol_1.Range.create(position.line, start, position.line, end); - } - gitCheck() { - let { uri } = this; - if (!uri.startsWith('file') || this.buftype != '') - return; - let filepath = vscode_uri_1.URI.parse(uri).fsPath; - fs_1.isGitIgnored(filepath).then(isIgnored => { - this.isIgnored = isIgnored; - }, () => { - this.isIgnored = false; - }); - } - createDocument(changeCount = 1) { - let { version, uri, filetype } = this; - version = version + changeCount; - this.textDocument = vscode_languageserver_textdocument_1.TextDocument.create(uri, filetype, version, this.getDocumentContent()); - } - async _fetchContent() { - if (!this.env.isVim || !this._attached) - return; - let { nvim, buffer } = this; - let { id } = buffer; - let o = (await nvim.call('coc#util#get_content', id)); - if (!o) - return; - let { content, changedtick } = o; - if (this._changedtick == changedtick) - return; - this._changedtick = changedtick; - let newLines = content.split('\n'); - this.lines = newLines; - this.fireContentChanges.clear(); - this._fireContentChanges(); - } - /** - * Get and synchronize change - */ - async patchChange(currentLine) { - if (!this._attached) - return; - if (this.env.isVim) { - if (currentLine) { - let change = await this.nvim.call('coc#util#get_changeinfo', []); - if (change.changedtick == this._changedtick) - return; - let { lines } = this; - let { lnum, line, changedtick } = change; - this._changedtick = changedtick; - lines[lnum - 1] = line; - this.forceSync(); - } - else { - this.fetchContent.clear(); - await this._fetchContent(); - } - } - else { - // we have latest lines aftet TextChange on neovim - this.forceSync(); - } - } - /** - * Get ranges of word in textDocument. - */ - getSymbolRanges(word) { - this.forceSync(); - let { textDocument } = this; - let res = []; - let content = textDocument.getText(); - let str = ''; - for (let i = 0, l = content.length; i < l; i++) { - let ch = content[i]; - if ('-' == ch && str.length == 0) { - continue; - } - let isKeyword = this.chars.isKeywordChar(ch); - if (isKeyword) { - str = str + ch; - } - if (str.length > 0 && !isKeyword && str == word) { - res.push(vscode_languageserver_protocol_1.Range.create(textDocument.positionAt(i - str.length), textDocument.positionAt(i))); - } - if (!isKeyword) { - str = ''; - } - } - return res; - } - /** - * Adjust col with new valid character before position. - */ - fixStartcol(position, valids) { - let line = this.getline(position.line); - if (!line) - return null; - let { character } = position; - let start = line.slice(0, character); - let col = string_1.byteLength(start); - let { chars } = this; - for (let i = start.length - 1; i >= 0; i--) { - let c = start[i]; - if (c == ' ') - break; - if (!chars.isKeywordChar(c) && !valids.includes(c)) { - break; - } - col = col - string_1.byteLength(c); - } - return col; - } - /** - * Use matchaddpos for highlight ranges, must use `redraw` command on vim - */ - matchAddRanges(ranges, hlGroup, priority = 10) { - let res = []; - let arr = []; - let splited = ranges.reduce((p, c) => { - for (let i = c.start.line; i <= c.end.line; i++) { - let curr = this.getline(i) || ''; - let sc = i == c.start.line ? c.start.character : 0; - let ec = i == c.end.line ? c.end.character : curr.length; - if (sc == ec) - continue; - p.push(vscode_languageserver_protocol_1.Range.create(i, sc, i, ec)); - } - return p; - }, []); - for (let range of splited) { - let { start, end } = range; - let line = this.getline(start.line); - if (start.character == end.character) - continue; - arr.push([start.line + 1, string_1.byteIndex(line, start.character) + 1, string_1.byteLength(line.slice(start.character, end.character))]); - } - for (let grouped of array_1.group(arr, 8)) { - let id = this.colorId; - this.colorId = this.colorId + 1; - this.nvim.call('matchaddpos', [hlGroup, grouped, priority, id], true); - res.push(id); - } - return res; - } - /** - * Highlight ranges in document, return match id list. - * - * Note: match id could by namespace id or vim's match id. - */ - highlightRanges(ranges, hlGroup, srcId, priority = 10) { - let res = []; - if (this.env.isVim && !this.env.textprop) { - res = this.matchAddRanges(ranges, hlGroup, priority); - } - else { - let lineRanges = []; - for (let range of ranges) { - if (range.start.line == range.end.line) { - lineRanges.push(range); - } - else { - // split range by lines - for (let i = range.start.line; i < range.end.line; i++) { - let line = this.getline(i); - if (i == range.start.line) { - lineRanges.push(vscode_languageserver_protocol_1.Range.create(i, range.start.character, i, line.length)); - } - else if (i == range.end.line) { - lineRanges.push(vscode_languageserver_protocol_1.Range.create(i, Math.min(line.match(/^\s*/)[0].length, range.end.character), i, range.end.character)); - } - else { - lineRanges.push(vscode_languageserver_protocol_1.Range.create(i, Math.min(line.match(/^\s*/)[0].length, line.length), i, line.length)); - } - } - } - } - for (let range of lineRanges) { - let { start, end } = range; - if (position_1.comparePosition(start, end) == 0) - continue; - let line = this.getline(start.line); - this.buffer.addHighlight({ - hlGroup, - srcId, - line: start.line, - colStart: string_1.byteIndex(line, start.character), - colEnd: end.line - start.line == 1 && end.character == 0 ? -1 : string_1.byteIndex(line, end.character) - }).logError(); - } - res.push(srcId); - } - return res; - } - /** - * Clear match id list, for vim support namespace, list should be namespace id list. - */ - clearMatchIds(ids) { - if (this.env.isVim && !this.env.textprop) { - this.nvim.call('coc#util#clear_buf_matches', [Array.from(ids), this.bufnr], true); - } - else { - ids = array_1.distinct(Array.from(ids)); - let hasNamesapce = this.nvim.hasFunction('nvim_create_namespace'); - ids.forEach(id => { - if (hasNamesapce) { - this.buffer.clearNamespace(id); - } - else { - this.buffer.clearHighlight({ srcId: id }); - } - }); - } - } - /** - * Get cwd of this document. - */ - async getcwd() { - let wid = await this.nvim.call('bufwinid', this.buffer.id); - if (wid == -1) - return await this.nvim.call('getcwd'); - return await this.nvim.call('getcwd', wid); - } - /** - * Real current line - */ - getline(line, current = true) { - if (current) - return this.lines[line] || ''; - let lines = this.textDocument.getText().split(/\r?\n/); - return lines[line] || ''; - } - /** - * Get lines, zero indexed, end exclude. - */ - getLines(start, end) { - return this.lines.slice(start, end); - } - /** - * Get current content text. - */ - getDocumentContent() { - let content = this.lines.join('\n'); - return this.eol ? content + '\n' : content; - } - /** - * Get variable value by key, defined by `b:coc_{key}` - */ - getVar(key, defaultValue) { - let val = this.variables[`coc_${key}`]; - return val === undefined ? defaultValue : val; - } - /** - * Get position from lnum & col - */ - getPosition(lnum, col) { - let line = this.getline(lnum - 1); - if (!line || col == 0) - return { line: lnum - 1, character: 0 }; - let pre = string_1.byteSlice(line, 0, col - 1); - return { line: lnum - 1, character: pre.length }; - } - /** - * Get end offset from cursor position. - * For normal mode, use offset -1 when possible - */ - getEndOffset(lnum, col, insert) { - let total = 0; - let len = this.lines.length; - for (let i = lnum - 1; i < len; i++) { - let line = this.lines[i]; - let l = line.length; - if (i == lnum - 1 && l != 0) { - // current - let buf = global.Buffer.from(line, 'utf8'); - let isEnd = buf.byteLength <= col - 1; - if (!isEnd) { - total = total + buf.slice(col - 1, buf.length).toString('utf8').length; - if (!insert) - total = total - 1; - } - } - else { - total = total + l; - } - if (!this.eol && i == len - 1) - break; - total = total + 1; - } - return total; - } - /** - * Recreate document with new filetype. - * - * @internal - */ - setFiletype(filetype) { - let { uri, version } = this; - this._filetype = this.convertFiletype(filetype); - version = version ? version + 1 : 1; - let textDocument = vscode_languageserver_textdocument_1.TextDocument.create(uri, this.filetype, version, this.content); - this.textDocument = textDocument; - } - /** - * Change iskeyword option of document - * - * @internal - */ - setIskeyword(iskeyword) { - let chars = this.chars = new chars_1.Chars(iskeyword); - let additional = this.getVar('additional_keywords', []); - if (additional && Array.isArray(additional)) { - for (let ch of additional) { - chars.addKeyword(ch); - } - } - let lines = this.lines.length > 30000 ? this.lines.slice(0, 30000) : this.lines; - this._words = this.chars.matchKeywords(lines.join('\n')); - } - /** - * Detach document. - * - * @internal - */ - detach() { - this._attached = false; - index_1.disposeAll(this.disposables); - this.disposables = []; - this.fetchContent.clear(); - this.fireContentChanges.clear(); - this._onDocumentChange.dispose(); - this._onDocumentDetach.dispose(); - } - get attached() { - return this._attached; - } - /** - * Get localify bonus map. - * - * @internal - */ - getLocalifyBonus(sp, ep) { - let res = new Map(); - let { chars } = this; - let startLine = Math.max(0, sp.line - 100); - let endLine = Math.min(this.lineCount, sp.line + 100); - let content = this.lines.slice(startLine, endLine).join('\n'); - sp = vscode_languageserver_protocol_1.Position.create(sp.line - startLine, sp.character); - ep = vscode_languageserver_protocol_1.Position.create(ep.line - startLine, ep.character); - let doc = vscode_languageserver_textdocument_1.TextDocument.create(this.uri, this.filetype, 1, content); - let headCount = doc.offsetAt(sp); - let len = content.length; - let tailCount = len - doc.offsetAt(ep); - let start = 0; - let preKeyword = false; - for (let i = 0; i < headCount; i++) { - let iskeyword = chars.isKeyword(content[i]); - if (!preKeyword && iskeyword) { - start = i; - } - else if (preKeyword && (!iskeyword || i == headCount - 1)) { - if (i - start > 1) { - let str = content.slice(start, i); - res.set(str, i / headCount); - } - } - preKeyword = iskeyword; - } - start = len - tailCount; - preKeyword = false; - for (let i = start; i < content.length; i++) { - let iskeyword = chars.isKeyword(content[i]); - if (!preKeyword && iskeyword) { - start = i; - } - else if (preKeyword && (!iskeyword || i == len - 1)) { - if (i - start > 1) { - let end = i == len - 1 ? i + 1 : i; - let str = content.slice(start, end); - let score = res.get(str) || 0; - res.set(str, Math.max(score, (len - i + (end - start)) / tailCount)); - } - } - preKeyword = iskeyword; - } - return res; - } -} -exports.default = Document; -//# sourceMappingURL=document.js.map - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.patchLine = exports.getChange = exports.diffLines = void 0; -const tslib_1 = __webpack_require__(65); -const fast_diff_1 = tslib_1.__importDefault(__webpack_require__(271)); -const string_1 = __webpack_require__(314); -const logger = __webpack_require__(64)('util-diff'); -function diffLines(oldLines, newLines) { - let start = 0; - let end = oldLines.length; - let oldLen = end; - let len = newLines.length; - for (let i = 0; i <= end; i++) { - if (newLines[i] !== oldLines[i]) { - start = i; - break; - } - if (i == end) { - start = end; - } - } - if (start != newLines.length) { - let maxRemain = Math.min(end - start, len - start); - for (let j = 0; j < maxRemain; j++) { - if (oldLines[oldLen - j - 1] != newLines[len - j - 1]) { - break; - } - end = end - 1; - } - } - return { - start, - end, - replacement: newLines.slice(start, len - (oldLen - end)) - }; -} -exports.diffLines = diffLines; -function getChange(oldStr, newStr, cursorEnd) { - let ol = oldStr.length; - let nl = newStr.length; - let max = Math.min(ol, nl); - let newText = ''; - let startOffset = 0; - let endOffset = -1; - let shouldLimit = false; - // find first endOffset, could <= this. one - for (let i = 0; i <= max; i++) { - if (cursorEnd != null && i == cursorEnd) { - endOffset = i; - shouldLimit = true; - break; - } - if (oldStr[ol - i - 1] != newStr[nl - i - 1]) { - endOffset = i; - break; - } - } - if (endOffset == -1) - return null; - // find start offset - let remain = max - endOffset; - if (remain == 0) { - startOffset = 0; - } - else { - for (let i = 0; i <= remain; i++) { - if (oldStr[i] != newStr[i] || i == remain) { - startOffset = i; - break; - } - } - } - // limit to minimal change - remain = remain - startOffset; - if (shouldLimit && remain > 0) { - let end = endOffset; - for (let i = 0; i < remain; i++) { - let oc = oldStr[ol - end - 1 - i]; - let nc = newStr[nl - end - 1 - i]; - if (oc == nc) { - endOffset = endOffset + 1; - } - else { - break; - } - } - } - let end = ol - endOffset; - if (ol == nl && startOffset == end) - return null; - newText = newStr.slice(startOffset, nl - endOffset); - // optimize for add new line(s) - if (startOffset == end) { - let pre = startOffset == 0 ? '' : newStr[startOffset - 1]; - if (pre && pre != '\n' - && oldStr[startOffset] == '\n' - && newText.startsWith('\n')) { - return { start: startOffset + 1, end: end + 1, newText: newText.slice(1) + '\n' }; - } - } - return { start: startOffset, end, newText }; -} -exports.getChange = getChange; -function patchLine(from, to, fill = ' ') { - if (from == to) - return to; - let idx = to.indexOf(from); - if (idx !== -1) - return fill.repeat(idx) + from; - let result = fast_diff_1.default(from, to); - let str = ''; - for (let item of result) { - if (item[0] == fast_diff_1.default.DELETE) { - // not allowed - return to; - } - else if (item[0] == fast_diff_1.default.INSERT) { - str = str + fill.repeat(string_1.byteLength(item[1])); - } - else { - str = str + item[1]; - } - } - return str; -} -exports.patchLine = patchLine; -//# sourceMappingURL=diff.js.map - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.equalsIgnoreCase = exports.isAsciiLetter = exports.isTriggerCharacter = exports.isWord = exports.byteSlice = exports.characterIndex = exports.indexOf = exports.byteIndex = exports.upperFirst = exports.byteLength = void 0; -// nvim use utf8 -function byteLength(str) { - return Buffer.byteLength(str); -} -exports.byteLength = byteLength; -function upperFirst(str) { - return str ? str[0].toUpperCase() + str.slice(1) : ''; -} -exports.upperFirst = upperFirst; -function byteIndex(content, index) { - let s = content.slice(0, index); - return Buffer.byteLength(s); -} -exports.byteIndex = byteIndex; -function indexOf(str, ch, count = 1) { - let curr = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] == ch) { - curr = curr + 1; - if (curr == count) { - return i; - } - } - } - return -1; -} -exports.indexOf = indexOf; -function characterIndex(content, byteIndex) { - let buf = Buffer.from(content, 'utf8'); - return buf.slice(0, byteIndex).toString('utf8').length; -} -exports.characterIndex = characterIndex; -function byteSlice(content, start, end) { - let buf = Buffer.from(content, 'utf8'); - return buf.slice(start, end).toString('utf8'); -} -exports.byteSlice = byteSlice; -function isWord(character) { - let code = character.charCodeAt(0); - if (code > 128) - return false; - if (code == 95) - return true; - if (code >= 48 && code <= 57) - return true; - if (code >= 65 && code <= 90) - return true; - if (code >= 97 && code <= 122) - return true; - return false; -} -exports.isWord = isWord; -function isTriggerCharacter(character) { - if (!character) - return false; - let code = character.charCodeAt(0); - if (code > 128) - return false; - if (code >= 65 && code <= 90) - return false; - if (code >= 97 && code <= 122) - return false; - return true; -} -exports.isTriggerCharacter = isTriggerCharacter; -function isAsciiLetter(code) { - if (code >= 65 && code <= 90) - return true; - if (code >= 97 && code <= 122) - return true; - return false; -} -exports.isAsciiLetter = isAsciiLetter; -function doEqualsIgnoreCase(a, b, stopAt = a.length) { - if (typeof a !== 'string' || typeof b !== 'string') { - return false; - } - for (let i = 0; i < stopAt; i++) { - const codeA = a.charCodeAt(i); - const codeB = b.charCodeAt(i); - if (codeA === codeB) { - continue; - } - // a-z A-Z - if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) { - const diff = Math.abs(codeA - codeB); - if (diff !== 0 && diff !== 32) { - return false; - } - } - // Any other charcode - else { - if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) { - return false; - } - } - } - return true; -} -function equalsIgnoreCase(a, b) { - const len1 = a ? a.length : 0; - const len2 = b ? b.length : 0; - if (len1 !== len2) { - return false; - } - return doEqualsIgnoreCase(a, b); -} -exports.equalsIgnoreCase = equalsIgnoreCase; -//# sourceMappingURL=string.js.map - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getChangedFromEdits = exports.editRange = exports.positionToOffset = exports.adjustPosition = exports.getChangedPosition = exports.isSingleLine = exports.comparePosition = exports.positionInRange = exports.emptyRange = exports.lineInRange = exports.rangeIntersect = exports.rangeOverlap = exports.rangeInRange = void 0; -function rangeInRange(r, range) { - return positionInRange(r.start, range) === 0 && positionInRange(r.end, range) === 0; -} -exports.rangeInRange = rangeInRange; -/** - * Check if two ranges have overlap character. - */ -function rangeOverlap(r, range) { - let { start, end } = r; - if (comparePosition(end, range.start) <= 0) { - return false; - } - if (comparePosition(start, range.end) >= 0) { - return false; - } - return true; -} -exports.rangeOverlap = rangeOverlap; -/** - * Check if two ranges have overlap or nested - */ -function rangeIntersect(r, range) { - if (positionInRange(r.start, range) == 0) { - return true; - } - if (positionInRange(r.end, range) == 0) { - return true; - } - if (rangeInRange(range, r)) { - return true; - } - return false; -} -exports.rangeIntersect = rangeIntersect; -function lineInRange(line, range) { - let { start, end } = range; - return line >= start.line && line <= end.line; -} -exports.lineInRange = lineInRange; -function emptyRange(range) { - let { start, end } = range; - return start.line == end.line && start.character == end.character; -} -exports.emptyRange = emptyRange; -function positionInRange(position, range) { - let { start, end } = range; - if (comparePosition(position, start) < 0) - return -1; - if (comparePosition(position, end) > 0) - return 1; - return 0; -} -exports.positionInRange = positionInRange; -function comparePosition(position, other) { - if (position.line > other.line) - return 1; - if (other.line == position.line && position.character > other.character) - return 1; - if (other.line == position.line && position.character == other.character) - return 0; - return -1; -} -exports.comparePosition = comparePosition; -function isSingleLine(range) { - return range.start.line == range.end.line; -} -exports.isSingleLine = isSingleLine; -function getChangedPosition(start, edit) { - let { range, newText } = edit; - if (comparePosition(range.end, start) <= 0) { - let lines = newText.split('\n'); - let lineCount = lines.length - (range.end.line - range.start.line) - 1; - let characterCount = 0; - if (range.end.line == start.line) { - let single = isSingleLine(range) && lineCount == 0; - let removed = single ? range.end.character - range.start.character : range.end.character; - let added = single ? newText.length : lines[lines.length - 1].length; - characterCount = added - removed; - } - return { line: lineCount, character: characterCount }; - } - return { line: 0, character: 0 }; -} -exports.getChangedPosition = getChangedPosition; -function adjustPosition(pos, edit) { - let { range, newText } = edit; - if (comparePosition(range.start, pos) > 1) - return pos; - let { start, end } = range; - let newLines = newText.split('\n'); - let delta = (end.line - start.line) - newLines.length + 1; - let lastLine = newLines[newLines.length - 1]; - let line = pos.line - delta; - if (pos.line != end.line) - return { line, character: pos.character }; - let pre = newLines.length == 1 && start.line != end.line ? start.character : 0; - let removed = start.line == end.line && newLines.length == 1 ? end.character - start.character : end.character; - let character = pre + pos.character + lastLine.length - removed; - return { - line, - character - }; -} -exports.adjustPosition = adjustPosition; -function positionToOffset(lines, line, character) { - let offset = 0; - for (let i = 0; i <= line; i++) { - if (i == line) { - offset += character; - } - else { - offset += lines[i].length + 1; - } - } - return offset; -} -exports.positionToOffset = positionToOffset; -// edit a range to newText -function editRange(range, text, edit) { - // outof range - if (!rangeInRange(edit.range, range)) - return text; - let { start, end } = edit.range; - let lines = text.split('\n'); - let character = start.line == range.start.line ? start.character - range.start.character : start.character; - let startOffset = positionToOffset(lines, start.line - range.start.line, character); - character = end.line == range.start.line ? end.character - range.start.character : end.character; - let endOffset = positionToOffset(lines, end.line - range.start.line, character); - return `${text.slice(0, startOffset)}${edit.newText}${text.slice(endOffset, text.length)}`; -} -exports.editRange = editRange; -function getChangedFromEdits(start, edits) { - let changed = { line: 0, character: 0 }; - for (let edit of edits) { - let d = getChangedPosition(start, edit); - changed = { line: changed.line + d.line, character: changed.character + d.character }; - } - return changed.line == 0 && changed.character == 0 ? null : changed; -} -exports.getChangedFromEdits = getChangedFromEdits; -//# sourceMappingURL=position.js.map - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Chars = exports.Range = void 0; -const logger = __webpack_require__(64)('model-chars'); -class Range { - constructor(start, end) { - this.start = start; - this.end = end ? end : start; - } - static fromKeywordOption(keywordOption) { - let parts = keywordOption.split(','); - let ranges = []; - for (let part of parts) { - if (part == '@') { - // isalpha() of c - ranges.push(new Range(65, 90)); - ranges.push(new Range(97, 122)); - } - else if (part == '@-@') { - ranges.push(new Range(64)); - } - else if (/^([A-Za-z])-([A-Za-z])$/.test(part)) { - let ms = part.match(/^([A-Za-z])-([A-Za-z])$/); - ranges.push(new Range(ms[1].charCodeAt(0), ms[2].charCodeAt(0))); - } - else if (/^\d+-\d+$/.test(part)) { - let ms = part.match(/^(\d+)-(\d+)$/); - ranges.push(new Range(Number(ms[1]), Number(ms[2]))); - } - else if (/^\d+$/.test(part)) { - ranges.push(new Range(Number(part))); - } - else { - let c = part.charCodeAt(0); - if (!ranges.some(o => o.contains(c))) { - ranges.push(new Range(c)); - } - } - } - return ranges; - } - contains(c) { - return c >= this.start && c <= this.end; - } -} -exports.Range = Range; -class Chars { - constructor(keywordOption) { - this.ranges = []; - if (keywordOption) - this.ranges = Range.fromKeywordOption(keywordOption); - } - addKeyword(ch) { - let c = ch.charCodeAt(0); - let { ranges } = this; - if (!ranges.some(o => o.contains(c))) { - ranges.push(new Range(c)); - } - } - clone() { - let chars = new Chars(); - chars.ranges = this.ranges.slice(); - return chars; - } - setKeywordOption(keywordOption) { - this.ranges = Range.fromKeywordOption(keywordOption); - } - matchKeywords(content, min = 3) { - let length = content.length; - if (length == 0) - return []; - let res = new Set(); - let str = ''; - let len = 0; - for (let i = 0; i < length; i++) { - let ch = content[i]; - let code = ch.codePointAt(0); - if (len == 0 && code == 45) - continue; - let isKeyword = this.isKeywordCode(code); - if (isKeyword) { - if (len == 48) - continue; - str = str + ch; - len = len + 1; - } - else { - if (len >= min && len < 48) - res.add(str); - str = ''; - len = 0; - } - } - if (len != 0) - res.add(str); - return Array.from(res); - } - isKeywordCode(code) { - if (code > 255) - return true; - if (code < 33) - return false; - return this.ranges.some(r => r.contains(code)); - } - isKeywordChar(ch) { - let { ranges } = this; - let c = ch.charCodeAt(0); - if (c > 255) - return true; - if (c < 33) - return false; - return ranges.some(r => r.contains(c)); - } - isKeyword(word) { - let { ranges } = this; - for (let i = 0, l = word.length; i < l; i++) { - let ch = word.charCodeAt(i); - // for speed - if (ch > 255) - return false; - if (ranges.some(r => r.contains(ch))) - continue; - return false; - } - return true; - } -} -exports.Chars = Chars; -//# sourceMappingURL=chars.js.map - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const floatFactory_1 = tslib_1.__importDefault(__webpack_require__(254)); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const logger = __webpack_require__(64)('model-menu'); -class Menu { - constructor(nvim, env) { - this.nvim = nvim; - this.env = env; - this._onDidChoose = new vscode_languageserver_protocol_1.Emitter(); - this._onDidCancel = new vscode_languageserver_protocol_1.Emitter(); - this.currIndex = 0; - this.total = 0; - this.onDidChoose = this._onDidChoose.event; - this.onDidCancel = this._onDidCancel.event; - let floatFactory = this.floatFactory = new floatFactory_1.default(nvim, env, false, 20, 80, false); - if (!env.isVim) { - nvim.command(`sign define CocCurrentLine linehl=PmenuSel`, true); - } - floatFactory.on('show', () => { - this.doHighlight(0); - choosed = undefined; - }); - floatFactory.on('close', () => { - firstNumber = undefined; - nvim.call('coc#list#stop_prompt', [], true); - if (choosed != null && choosed < this.total) { - this._onDidChoose.fire(choosed); - choosed = undefined; - } - else { - this._onDidCancel.fire(); - } - }); - let timer; - let firstNumber; - let choosed; - events_1.default.on('MenuInput', (character, mode) => { - if (mode) - return; - if (timer) - clearTimeout(timer); - // esc & `` - if (character == '\x1b' || character == '\x03' || !this.window) { - this.hide(); - return; - } - if (character == '\r') { - choosed = this.currIndex; - this.hide(); - return; - } - if (character >= '0' && character <= '9') { - let n = parseInt(character, 10); - if (isNaN(n) || n > this.total) - return; - if (firstNumber == null && n == 0) - return; - if (firstNumber) { - let count = firstNumber * 10 + n; - firstNumber = undefined; - choosed = count - 1; - this.hide(); - return; - } - if (this.total < 10 || n * 10 > this.total) { - choosed = n - 1; - this.hide(); - return; - } - timer = setTimeout(async () => { - choosed = n - 1; - this.hide(); - firstNumber = undefined; - }, 200); - firstNumber = n; - return; - } - firstNumber = undefined; - if (character == 'G') { - this.currIndex = this.total - 1; - } - else if (['j', '\x0e', '\t'].includes(character)) { - this.currIndex = this.currIndex >= this.total - 1 ? 0 : this.currIndex + 1; - } - else if (['k', '\x10'].includes(character)) { - this.currIndex = this.currIndex == 0 ? this.total - 1 : this.currIndex - 1; - } - else { - return; - } - nvim.pauseNotification(); - if (this.env.isVim) { - nvim.call('win_execute', [this.window.id, `exe ${this.currIndex + 1}`], true); - } - else { - nvim.call('coc#util#win_gotoid', [this.window.id], true); - nvim.call('cursor', [this.currIndex + 1, 1], true); - this.doHighlight(this.currIndex); - nvim.command('noa wincmd p', true); - } - nvim.command('redraw', true); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true); - }); - } - get window() { - return this.floatFactory.window; - } - doHighlight(index) { - let { nvim } = this; - if (this.env.isVim) - return; - let buf = this.floatFactory.buffer; - if (!buf) - return; - nvim.command(`sign unplace 6 buffer=${buf.id}`, true); - nvim.command(`sign place 6 line=${index + 1} name=CocCurrentLine buffer=${buf.id}`, true); - } - show(items, title) { - let lines = items.map((v, i) => { - if (i < 99) - return `${i + 1}. ${v}`; - return v; - }); - this.total = lines.length; - this.currIndex = 0; - this.floatFactory.show([{ - content: lines.join('\n'), - filetype: 'menu' - }], { title, cursorline: this.env.isVim }).then(() => { - if (this.window) { - this.nvim.call('coc#list#start_prompt', ['MenuInput'], true); - } - else { - // failed to create window - this._onDidCancel.fire(); - } - }, e => { - logger.error(e); - }); - } - hide() { - this.nvim.call('coc#list#stop_prompt', [], true); - this.floatFactory.close(); - } -} -exports.default = Menu; -//# sourceMappingURL=menu.js.map - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const minimatch_1 = tslib_1.__importDefault(__webpack_require__(283)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const util_1 = __webpack_require__(238); -const array_1 = __webpack_require__(257); -const logger = __webpack_require__(64)('filesystem-watcher'); -class FileSystemWatcher { - constructor(clientPromise, globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents) { - this.globPattern = globPattern; - this.ignoreCreateEvents = ignoreCreateEvents; - this.ignoreChangeEvents = ignoreChangeEvents; - this.ignoreDeleteEvents = ignoreDeleteEvents; - this._onDidCreate = new vscode_languageserver_protocol_1.Emitter(); - this._onDidChange = new vscode_languageserver_protocol_1.Emitter(); - this._onDidDelete = new vscode_languageserver_protocol_1.Emitter(); - this._onDidRename = new vscode_languageserver_protocol_1.Emitter(); - this.onDidCreate = this._onDidCreate.event; - this.onDidChange = this._onDidChange.event; - this.onDidDelete = this._onDidDelete.event; - this.onDidRename = this._onDidRename.event; - this.disposables = []; - if (!clientPromise) - return; - clientPromise.then(client => { - if (client) - return this.listen(client); - }).catch(error => { - logger.error('watchman initialize failed'); - logger.error(error.stack); - }); - } - async listen(client) { - let { globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents } = this; - let disposable = await client.subscribe(globPattern, (change) => { - let { root, files } = change; - files = files.filter(f => f.type == 'f' && minimatch_1.default(f.name, globPattern, { dot: true })); - for (let file of files) { - let uri = vscode_uri_1.URI.file(path_1.default.join(root, file.name)); - if (!file.exists) { - if (!ignoreDeleteEvents) - this._onDidDelete.fire(uri); - } - else { - if (file.new === true) { - if (!ignoreCreateEvents) - this._onDidCreate.fire(uri); - } - else { - if (!ignoreChangeEvents) - this._onDidChange.fire(uri); - } - } - } - // file rename - if (files.length == 2 && !files[0].exists && files[1].exists) { - let oldFile = files[0]; - let newFile = files[1]; - if (oldFile.size == newFile.size) { - this._onDidRename.fire({ - oldUri: vscode_uri_1.URI.file(path_1.default.join(root, oldFile.name)), - newUri: vscode_uri_1.URI.file(path_1.default.join(root, newFile.name)) - }); - } - } - // detect folder rename - if (files.length >= 2) { - let [oldFiles, newFiles] = array_1.splitArray(files, o => o.exists === false); - if (oldFiles.length == newFiles.length) { - for (let oldFile of oldFiles) { - let newFile = newFiles.find(o => o.size == oldFile.size && o.mtime_ms == oldFile.mtime_ms); - if (newFile) { - this._onDidRename.fire({ - oldUri: vscode_uri_1.URI.file(path_1.default.join(root, oldFile.name)), - newUri: vscode_uri_1.URI.file(path_1.default.join(root, newFile.name)) - }); - } - } - } - } - }); - this.disposables.push(disposable); - return disposable; - } - dispose() { - util_1.disposeAll(this.disposables); - } -} -exports.default = FileSystemWatcher; -//# sourceMappingURL=fileSystemWatcher.js.map - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const util_1 = tslib_1.__importDefault(__webpack_require__(74)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -/** - * Mru - manage string items as lines in mru file. - */ -class Mru { - /** - * @param {string} name unique name - * @param {string} base? optional directory name, default to config root of coc.nvim - */ - constructor(name, base) { - this.name = name; - this.file = path_1.default.join(base || process.env.COC_DATA_HOME, name); - } - /** - * Load iems from mru file - */ - async load() { - let dir = path_1.default.dirname(this.file); - try { - mkdirp_1.default.sync(dir); - if (!fs_1.default.existsSync(this.file)) { - fs_1.default.writeFileSync(this.file, '', 'utf8'); - } - let content = await util_1.default.promisify(fs_1.default.readFile)(this.file, 'utf8'); - content = content.trim(); - return content.length ? content.trim().split('\n') : []; - } - catch (e) { - return []; - } - } - /** - * Add item to mru file. - */ - async add(item) { - let items = await this.load(); - let idx = items.indexOf(item); - if (idx !== -1) - items.splice(idx, 1); - items.unshift(item); - fs_1.default.writeFileSync(this.file, items.join('\n'), 'utf8'); - } - /** - * Remove item from mru file. - */ - async remove(item) { - let items = await this.load(); - let idx = items.indexOf(item); - if (idx !== -1) { - items.splice(idx, 1); - fs_1.default.writeFileSync(this.file, items.join('\n'), 'utf8'); - } - } - /** - * Remove the data file. - */ - async clean() { - try { - await util_1.default.promisify(fs_1.default.unlink)(this.file); - } - catch (e) { - // noop - } - } -} -exports.default = Mru; -//# sourceMappingURL=mru.js.map - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const util_1 = __webpack_require__(238); -const fs_1 = __webpack_require__(306); -const decorator_1 = __webpack_require__(321); -const logger = __webpack_require__(64)('model-resolver'); -class Resolver { - get nodeFolder() { - if (!util_1.executable('npm')) - return Promise.resolve(''); - return util_1.runCommand('npm --loglevel silent root -g', {}, 3000).then(root => root.trim()); - } - get yarnFolder() { - if (!util_1.executable('yarnpkg')) - return Promise.resolve(''); - return util_1.runCommand('yarnpkg global dir', {}, 3000).then(root => path_1.default.join(root.trim(), 'node_modules')); - } - async resolveModule(mod) { - let nodeFolder = await this.nodeFolder; - let yarnFolder = await this.yarnFolder; - if (yarnFolder) { - let s = await fs_1.statAsync(path_1.default.join(yarnFolder, mod, 'package.json')); - if (s && s.isFile()) - return path_1.default.join(yarnFolder, mod); - } - if (nodeFolder) { - let s = await fs_1.statAsync(path_1.default.join(nodeFolder, mod, 'package.json')); - if (s && s.isFile()) - return path_1.default.join(nodeFolder, mod); - } - return null; - } -} -tslib_1.__decorate([ - decorator_1.memorize -], Resolver.prototype, "nodeFolder", null); -tslib_1.__decorate([ - decorator_1.memorize -], Resolver.prototype, "yarnFolder", null); -exports.default = Resolver; -//# sourceMappingURL=resolver.js.map - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.memorize = void 0; -const logger = __webpack_require__(64)('util-decorator'); -function memorize(_target, key, descriptor) { - let fn = descriptor.value; - if (typeof fn !== 'function') - return; - let memoKey = '$' + key; - descriptor.value = function (...args) { - if (this.hasOwnProperty(memoKey)) - return Promise.resolve(this[memoKey]); - return new Promise((resolve, reject) => { - Promise.resolve(fn.apply(this, args)).then(res => { - this[memoKey] = res; - resolve(res); - }, e => { - reject(e); - }); - }); - }; -} -exports.memorize = memorize; -//# sourceMappingURL=decorator.js.map - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.frames = void 0; -const uuid_1 = __webpack_require__(259); -const logger = __webpack_require__(64)('model-status'); -exports.frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; -class StatusLine { - constructor(nvim) { - this.nvim = nvim; - this.items = new Map(); - this.shownIds = new Set(); - this._text = ''; - this.interval = setInterval(() => { - this.setStatusText().logError(); - }, 100); - } - dispose() { - clearInterval(this.interval); - } - createStatusBarItem(priority = 0, isProgress = false) { - let uid = uuid_1.v1(); - let item = { - text: '', - priority, - isProgress, - show: () => { - this.shownIds.add(uid); - }, - hide: () => { - this.shownIds.delete(uid); - }, - dispose: () => { - this.shownIds.delete(uid); - this.items.delete(uid); - } - }; - this.items.set(uid, item); - return item; - } - getText() { - if (this.shownIds.size == 0) - return ''; - let d = new Date(); - let idx = Math.floor(d.getMilliseconds() / 100); - let text = ''; - let items = []; - for (let [id, item] of this.items) { - if (this.shownIds.has(id)) { - items.push(item); - } - } - items.sort((a, b) => a.priority - b.priority); - for (let item of items) { - if (!item.isProgress) { - text = `${text} ${item.text}`; - } - else { - text = `${text} ${exports.frames[idx]} ${item.text}`; - } - } - return text; - } - async setStatusText() { - let text = this.getText(); - let { nvim } = this; - if (text != this._text) { - this._text = text; - nvim.pauseNotification(); - this.nvim.setVar('coc_status', text, true); - this.nvim.call('coc#util#do_autocmd', ['CocStatusChange'], true); - await nvim.resumeNotification(false, true); - } - } -} -exports.default = StatusLine; -//# sourceMappingURL=status.js.map - -/***/ }), -/* 323 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const util_1 = __webpack_require__(238); -/** - * Controls long running task started by vim. - * Useful to keep the task running after CocRestart. - * - * @public - */ -class Task { - /** - * @param {Neovim} nvim - * @param {string} id unique id - */ - constructor(nvim, id) { - this.nvim = nvim; - this.id = id; - this.disposables = []; - this._onExit = new vscode_languageserver_protocol_1.Emitter(); - this._onStderr = new vscode_languageserver_protocol_1.Emitter(); - this._onStdout = new vscode_languageserver_protocol_1.Emitter(); - this.onExit = this._onExit.event; - this.onStdout = this._onStdout.event; - this.onStderr = this._onStderr.event; - events_1.default.on('TaskExit', (id, code) => { - if (id == this.id) { - this._onExit.fire(code); - } - }, null, this.disposables); - events_1.default.on('TaskStderr', (id, lines) => { - if (id == this.id) { - this._onStderr.fire(lines); - } - }, null, this.disposables); - let stdout = []; - let timer; - events_1.default.on('TaskStdout', (id, lines) => { - if (id == this.id) { - if (timer) - clearTimeout(timer); - stdout.push(...lines); - timer = setTimeout(() => { - this._onStdout.fire(stdout); - stdout = []; - }, 100); - } - }, null, this.disposables); - } - /** - * Start task, task will be restarted when already running. - * - * @param {TaskOptions} opts - * @returns {Promise} - */ - async start(opts) { - let { nvim } = this; - return await nvim.call('coc#task#start', [this.id, opts]); - } - /** - * Stop task by SIGTERM or SIGKILL - */ - async stop() { - let { nvim } = this; - await nvim.call('coc#task#stop', [this.id]); - } - /** - * Check if the task is running. - */ - get running() { - let { nvim } = this; - return nvim.call('coc#task#running', [this.id]); - } - /** - * Stop task and dispose all events. - */ - dispose() { - let { nvim } = this; - nvim.call('coc#task#stop', [this.id], true); - this._onStdout.dispose(); - this._onStderr.dispose(); - this._onExit.dispose(); - util_1.disposeAll(this.disposables); - } -} -exports.default = Task; -//# sourceMappingURL=task.js.map - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const logger = __webpack_require__(64)('model-terminal'); -class TerminalModel { - constructor(cmd, args, nvim, _name) { - this.cmd = cmd; - this.args = args; - this.nvim = nvim; - this._name = _name; - this.pid = 0; - } - async start(cwd, env) { - let { nvim } = this; - let cmd = [this.cmd, ...this.args]; - let [bufnr, pid] = await nvim.call('coc#terminal#start', [cmd, cwd, env || {}]); - this.bufnr = bufnr; - this.pid = pid; - } - get name() { - return this._name || this.cmd; - } - get processId() { - return Promise.resolve(this.pid); - } - sendText(text, addNewLine = true) { - if (!this.bufnr) - return; - this.nvim.call('coc#terminal#send', [this.bufnr, text, addNewLine], true); - } - async show(preserveFocus) { - let { bufnr, nvim } = this; - if (!bufnr) - return; - let [loaded, winid, curr] = await nvim.eval(`[bufloaded(${bufnr}),bufwinid(${bufnr}),win_getid()]`); - if (!loaded) - return false; - if (curr == winid) - return true; - nvim.pauseNotification(); - if (winid == -1) { - nvim.command(`below ${bufnr}sb`, true); - nvim.command('resize 8', true); - nvim.call('coc#util#do_autocmd', ['CocTerminalOpen'], true); - } - else { - nvim.call('win_gotoid', [winid], true); - } - nvim.command('normal! G', true); - if (preserveFocus) { - nvim.command('wincmd p', true); - } - await nvim.resumeNotification(); - return true; - } - async hide() { - let { bufnr, nvim } = this; - if (!bufnr) - return; - let winnr = await nvim.call('bufwinnr', bufnr); - if (winnr == -1) - return; - await nvim.command(`${winnr}close!`); - } - dispose() { - let { bufnr, nvim } = this; - if (!bufnr) - return; - nvim.call('coc#terminal#close', [bufnr], true); - } -} -exports.default = TerminalModel; -//# sourceMappingURL=terminal.js.map - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const util_1 = __webpack_require__(238); -const logger = __webpack_require__(64)('willSaveHandler'); -class WillSaveUntilHandler { - constructor(workspace) { - this.workspace = workspace; - this.callbacks = []; - } - addCallback(callback, thisArg, clientId) { - let fn = (event) => { - let { workspace } = this; - let ev = Object.assign({}, event); - return new Promise(resolve => { - let called = false; - ev.waitUntil = (thenable) => { - called = true; - let { document } = ev; - let timer = setTimeout(() => { - workspace.showMessage(`${clientId} will save operation timeout after 0.5s`, 'warning'); - resolve(null); - }, 500); - Promise.resolve(thenable).then((edits) => { - clearTimeout(timer); - let doc = workspace.getDocument(document.uri); - if (doc && edits && vscode_languageserver_protocol_1.TextEdit.is(edits[0])) { - doc.applyEdits(edits).then(() => { - // make sure server received ChangedText - setTimeout(resolve, 50); - }, e => { - logger.error(e); - workspace.showMessage(`${clientId} error on applyEdits ${e.message}`, 'error'); - resolve(); - }); - } - else { - resolve(); - } - }, e => { - clearTimeout(timer); - logger.error(`${clientId} error on willSaveUntil ${e.message}`, 'error'); - resolve(); - }); - }; - callback.call(thisArg, ev); - if (!called) { - resolve(); - } - }); - }; - this.callbacks.push(fn); - return vscode_languageserver_protocol_1.Disposable.create(() => { - let idx = this.callbacks.indexOf(fn); - if (idx != -1) { - this.callbacks.splice(idx, 1); - } - }); - } - get hasCallback() { - let { callbacks } = this; - return callbacks.length > 0; - } - async handeWillSaveUntil(event) { - let { callbacks, workspace } = this; - let { document } = event; - if (!callbacks.length) - return; - let doc = workspace.getDocument(document.uri); - if (!doc) - return; - let now = Date.now(); - await doc.patchChange(); - await util_1.wait(60); - for (let fn of callbacks) { - event.document = doc.textDocument; - try { - await fn(event); - } - catch (e) { - logger.error(e); - } - } - logger.info(`Will save cost: ${Date.now() - now}`); - } -} -exports.default = WillSaveUntilHandler; -//# sourceMappingURL=willSaveHandler.js.map - -/***/ }), -/* 326 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.score = void 0; -const tslib_1 = __webpack_require__(65); -const minimatch_1 = tslib_1.__importDefault(__webpack_require__(283)); -const vscode_uri_1 = __webpack_require__(243); -const platform = tslib_1.__importStar(__webpack_require__(248)); -function score(selector, uri, languageId) { - if (Array.isArray(selector)) { - // array -> take max individual value - let ret = 0; - for (const filter of selector) { - const value = score(filter, uri, languageId); - if (value === 10) { - return value; // already at the highest - } - if (value > ret) { - ret = value; - } - } - return ret; - } - else if (typeof selector === 'string') { - // short-hand notion, desugars to - // 'fooLang' -> { language: 'fooLang'} - // '*' -> { language: '*' } - if (selector === '*') { - return 5; - } - else if (selector === languageId) { - return 10; - } - else { - return 0; - } - } - else if (selector) { - let u = vscode_uri_1.URI.parse(uri); - // filter -> select accordingly, use defaults for scheme - const { language, pattern, scheme } = selector; - let ret = 0; - if (scheme) { - if (scheme === u.scheme) { - ret = 5; - } - else if (scheme === '*') { - ret = 3; - } - else { - return 0; - } - } - if (language) { - if (language === languageId) { - ret = 10; - } - else if (language === '*') { - ret = Math.max(ret, 5); - } - else { - return 0; - } - } - if (pattern) { - let caseInsensitive = platform.isWindows || platform.isMacintosh; - let p = caseInsensitive ? pattern.toLowerCase() : pattern; - let f = caseInsensitive ? u.fsPath.toLowerCase() : u.fsPath; - if (p === f || minimatch_1.default(f, p, { dot: true })) { - ret = 5; - } - else { - return 0; - } - } - return ret; - } - else { - return 0; - } -} -exports.score = score; -//# sourceMappingURL=match.js.map - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isValidWatchRoot = void 0; -const tslib_1 = __webpack_require__(65); -const fb_watchman_1 = tslib_1.__importDefault(__webpack_require__(328)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const uuid_1 = __webpack_require__(259); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const minimatch_1 = tslib_1.__importDefault(__webpack_require__(283)); -const fs_1 = __webpack_require__(306); -const logger = __webpack_require__(64)('watchman'); -const requiredCapabilities = ['relative_root', 'cmd-watch-project', 'wildmatch', 'field-new']; -const clientsMap = new Map(); -/** - * Watchman wrapper for fb-watchman client - * - * @public - */ -class Watchman { - constructor(binaryPath, channel) { - this.channel = channel; - this._disposed = false; - this.client = new fb_watchman_1.default.Client({ - watchmanBinaryPath: binaryPath - }); - this.client.setMaxListeners(300); - } - checkCapability() { - let { client } = this; - return new Promise((resolve, reject) => { - client.capabilityCheck({ - optional: [], - required: requiredCapabilities - }, (error, resp) => { - if (error) - return reject(error); - let { capabilities } = resp; - for (let key of Object.keys(capabilities)) { - if (!capabilities[key]) - return resolve(false); - } - resolve(true); - }); - }); - } - async watchProject(root) { - try { - let resp = await this.command(['watch-project', root]); - let { watch, warning, relative_path } = resp; - if (warning) - logger.warn(warning); - this.watch = watch; - this.relative_path = relative_path; - logger.info(`watchman watching project: ${root}`); - this.appendOutput(`watchman watching project: ${root}`); - } - catch (e) { - logger.error(e); - return false; - } - return true; - } - command(args) { - return new Promise((resolve, reject) => { - this.client.command(args, (error, resp) => { - if (error) - return reject(error); - resolve(resp); - }); - }); - } - async subscribe(globPattern, cb) { - let { watch, relative_path } = this; - if (!watch) { - this.appendOutput(`watchman not watching: ${watch}`, 'Error'); - return null; - } - let { clock } = await this.command(['clock', watch]); - let uid = uuid_1.v1(); - let sub = { - expression: ['allof', ['match', '**/*', 'wholename']], - fields: ['name', 'size', 'new', 'exists', 'type', 'mtime_ms', 'ctime_ms'], - since: clock, - }; - let root = watch; - if (relative_path) { - sub.relative_root = relative_path; - root = path_1.default.join(watch, relative_path); - } - let { subscribe } = await this.command(['subscribe', watch, uid, sub]); - if (global.hasOwnProperty('__TEST__')) - global.subscribe = subscribe; - this.appendOutput(`subscribing "${globPattern}" in ${root}`); - this.client.on('subscription', resp => { - if (!resp || resp.subscription != uid) - return; - let { files } = resp; - if (!files) - return; - files = files.filter(f => f.type == 'f' && minimatch_1.default(f.name, globPattern, { dot: true })); - if (!files.length) - return; - let ev = Object.assign({}, resp); - if (this.relative_path) - ev.root = path_1.default.resolve(resp.root, this.relative_path); - this.appendOutput(`file change detected: ${JSON.stringify(ev, null, 2)}`); - cb(ev); - }); - return vscode_languageserver_protocol_1.Disposable.create(() => this.unsubscribe(subscribe)); - } - unsubscribe(subscription) { - if (this._disposed) - return Promise.resolve(); - let { watch } = this; - if (!watch) - return; - this.appendOutput(`unsubscribe "${subscription}" in: ${watch}`); - return this.command(['unsubscribe', watch, subscription]).catch(e => { - logger.error(e); - }); - } - dispose() { - this._disposed = true; - this.client.removeAllListeners(); - this.client.end(); - } - appendOutput(message, type = "Info") { - if (this.channel) { - this.channel.appendLine(`[${type} - ${(new Date().toLocaleTimeString())}] ${message}`); - } - } - static dispose() { - for (let promise of clientsMap.values()) { - promise.then(client => { - client.dispose(); - }, _e => { - // noop - }); - } - } - static createClient(binaryPath, root, channel) { - if (!isValidWatchRoot(root)) - return null; - let client = clientsMap.get(root); - if (client) - return client; - let promise = new Promise(async (resolve, reject) => { - try { - let watchman = new Watchman(binaryPath, channel); - let valid = await watchman.checkCapability(); - if (!valid) - return resolve(null); - let watching = await watchman.watchProject(root); - if (!watching) - return resolve(null); - resolve(watchman); - } - catch (e) { - reject(e); - } - }); - clientsMap.set(root, promise); - return promise; - } -} -exports.default = Watchman; -/** - * Exclude user's home, driver, tmpdir - */ -function isValidWatchRoot(root) { - if (root == '/' || root == '/tmp' || root == '/private/tmp') - return false; - if (root.toLowerCase() === os_1.default.homedir().toLowerCase()) - return false; - if (path_1.default.parse(root).base == root) - return false; - if (root.startsWith('/tmp/') || root.startsWith('/private/tmp/')) - return false; - if (fs_1.isParentFolder(os_1.default.tmpdir(), root, true)) - return false; - return true; -} -exports.isValidWatchRoot = isValidWatchRoot; -//# sourceMappingURL=watchman.js.map - -/***/ }), -/* 328 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* Copyright 2014-present Facebook, Inc. - * Licensed under the Apache License, Version 2.0 */ - - - -var net = __webpack_require__(157); -var EE = __webpack_require__(198).EventEmitter; -var util = __webpack_require__(74); -var childProcess = __webpack_require__(239); -var bser = __webpack_require__(329); - -// We'll emit the responses to these when they get sent down to us -var unilateralTags = ['subscription', 'log']; - -/** - * @param options An object with the following optional keys: - * * 'watchmanBinaryPath' (string) Absolute path to the watchman binary. - * If not provided, the Client locates the binary using the PATH specified - * by the node child_process's default env. - */ -function Client(options) { - var self = this; - EE.call(this); - - this.watchmanBinaryPath = 'watchman'; - if (options && options.watchmanBinaryPath) { - this.watchmanBinaryPath = options.watchmanBinaryPath.trim(); - }; - this.commands = []; -} -util.inherits(Client, EE); - -module.exports.Client = Client; - -// Try to send the next queued command, if any -Client.prototype.sendNextCommand = function() { - if (this.currentCommand) { - // There's a command pending response, don't send this new one yet - return; - } - - this.currentCommand = this.commands.shift(); - if (!this.currentCommand) { - // No further commands are queued - return; - } - - this.socket.write(bser.dumpToBuffer(this.currentCommand.cmd)); -} - -Client.prototype.cancelCommands = function(why) { - var error = new Error(why); - - // Steal all pending commands before we start cancellation, in - // case something decides to schedule more commands - var cmds = this.commands; - this.commands = []; - - if (this.currentCommand) { - cmds.unshift(this.currentCommand); - this.currentCommand = null; - } - - // Synthesize an error condition for any commands that were queued - cmds.forEach(function(cmd) { - cmd.cb(error); - }); -} - -Client.prototype.connect = function() { - var self = this; - - function makeSock(sockname) { - // bunser will decode the watchman BSER protocol for us - self.bunser = new bser.BunserBuf(); - // For each decoded line: - self.bunser.on('value', function(obj) { - // Figure out if this is a unliteral response or if it is the - // response portion of a request-response sequence. At the time - // of writing, there are only two possible unilateral responses. - var unilateral = false; - for (var i = 0; i < unilateralTags.length; i++) { - var tag = unilateralTags[i]; - if (tag in obj) { - unilateral = tag; - } - } - - if (unilateral) { - self.emit(unilateral, obj); - } else if (self.currentCommand) { - var cmd = self.currentCommand; - self.currentCommand = null; - if ('error' in obj) { - var error = new Error(obj.error); - error.watchmanResponse = obj; - cmd.cb(error); - } else { - cmd.cb(null, obj); - } - } - - // See if we can dispatch the next queued command, if any - self.sendNextCommand(); - }); - self.bunser.on('error', function(err) { - self.emit('error', err); - }); - - self.socket = net.createConnection(sockname); - self.socket.on('connect', function() { - self.connecting = false; - self.emit('connect'); - self.sendNextCommand(); - }); - self.socket.on('error', function(err) { - self.connecting = false; - self.emit('error', err); - }); - self.socket.on('data', function(buf) { - if (self.bunser) { - self.bunser.append(buf); - } - }); - self.socket.on('end', function() { - self.socket = null; - self.bunser = null; - self.cancelCommands('The watchman connection was closed'); - self.emit('end'); - }); - } - - // triggers will export the sock path to the environment. - // If we're invoked in such a way, we can simply pick up the - // definition from the environment and avoid having to fork off - // a process to figure it out - if (process.env.WATCHMAN_SOCK) { - makeSock(process.env.WATCHMAN_SOCK); - return; - } - - // We need to ask the client binary where to find it. - // This will cause the service to start for us if it isn't - // already running. - var args = ['--no-pretty', 'get-sockname']; - - // We use the more elaborate spawn rather than exec because there - // are some error cases on Windows where process spawning can hang. - // It is desirable to pipe stderr directly to stderr live so that - // we can discover the problem. - var proc = null; - var spawnFailed = false; - - function spawnError(error) { - if (spawnFailed) { - // For ENOENT, proc 'close' will also trigger with a negative code, - // let's suppress that second error. - return; - } - spawnFailed = true; - if (error.errno === 'EACCES') { - error.message = 'The Watchman CLI is installed but cannot ' + - 'be spawned because of a permission problem'; - } else if (error.errno === 'ENOENT') { - error.message = 'Watchman was not found in PATH. See ' + - 'https://facebook.github.io/watchman/docs/install.html ' + - 'for installation instructions'; - } - console.error('Watchman: ', error.message); - self.emit('error', error); - } - - try { - proc = childProcess.spawn(this.watchmanBinaryPath, args, { - stdio: ['ignore', 'pipe', 'pipe'] - }); - } catch (error) { - spawnError(error); - return; - } - - var stdout = []; - var stderr = []; - proc.stdout.on('data', function(data) { - stdout.push(data); - }); - proc.stderr.on('data', function(data) { - data = data.toString('utf8'); - stderr.push(data); - console.error(data); - }); - proc.on('error', function(error) { - spawnError(error); - }); - - proc.on('close', function (code, signal) { - if (code !== 0) { - spawnError(new Error( - self.watchmanBinaryPath + ' ' + args.join(' ') + - ' returned with exit code=' + code + ', signal=' + - signal + ', stderr= ' + stderr.join(''))); - return; - } - try { - var obj = JSON.parse(stdout.join('')); - if ('error' in obj) { - var error = new Error(obj.error); - error.watchmanResponse = obj; - self.emit('error', error); - return; - } - makeSock(obj.sockname); - } catch (e) { - self.emit('error', e); - } - }); -} - -Client.prototype.command = function(args, done) { - done = done || function() {}; - - // Queue up the command - this.commands.push({cmd: args, cb: done}); - - // Establish a connection if we don't already have one - if (!this.socket) { - if (!this.connecting) { - this.connecting = true; - this.connect(); - return; - } - return; - } - - // If we're already connected and idle, try sending the command immediately - this.sendNextCommand(); -} - -var cap_versions = { - "cmd-watch-del-all": "3.1.1", - "cmd-watch-project": "3.1", - "relative_root": "3.3", - "term-dirname": "3.1", - "term-idirname": "3.1", - "wildmatch": "3.7", -} - -// Compares a vs b, returns < 0 if a < b, > 0 if b > b, 0 if a == b -function vers_compare(a, b) { - a = a.split('.'); - b = b.split('.'); - for (var i = 0; i < 3; i++) { - var d = parseInt(a[i] || '0') - parseInt(b[i] || '0'); - if (d != 0) { - return d; - } - } - return 0; // Equal -} - -function have_cap(vers, name) { - if (name in cap_versions) { - return vers_compare(vers, cap_versions[name]) >= 0; - } - return false; -} - -// This is a helper that we expose for testing purposes -Client.prototype._synthesizeCapabilityCheck = function( - resp, optional, required) { - resp.capabilities = {} - var version = resp.version; - optional.forEach(function (name) { - resp.capabilities[name] = have_cap(version, name); - }); - required.forEach(function (name) { - var have = have_cap(version, name); - resp.capabilities[name] = have; - if (!have) { - resp.error = 'client required capability `' + name + - '` is not supported by this server'; - } - }); - return resp; -} - -Client.prototype.capabilityCheck = function(caps, done) { - var optional = caps.optional || []; - var required = caps.required || []; - var self = this; - this.command(['version', { - optional: optional, - required: required - }], function (error, resp) { - if (error) { - done(error); - return; - } - if (!('capabilities' in resp)) { - // Server doesn't support capabilities, so we need to - // synthesize the results based on the version - resp = self._synthesizeCapabilityCheck(resp, optional, required); - if (resp.error) { - error = new Error(resp.error); - error.watchmanResponse = resp; - done(error); - return; - } - } - done(null, resp); - }); -} - -// Close the connection to the service -Client.prototype.end = function() { - this.cancelCommands('The client was ended'); - if (this.socket) { - this.socket.end(); - this.socket = null; - } - this.bunser = null; -} - - -/***/ }), -/* 329 */ -/***/ (function(module, exports, __webpack_require__) { - -/* Copyright 2015-present Facebook, Inc. - * Licensed under the Apache License, Version 2.0 */ - -var EE = __webpack_require__(198).EventEmitter; -var util = __webpack_require__(74); -var os = __webpack_require__(76); -var assert = __webpack_require__(108); -var Int64 = __webpack_require__(330); - -// BSER uses the local endianness to reduce byte swapping overheads -// (the protocol is expressly local IPC only). We need to tell node -// to use the native endianness when reading various native values. -var isBigEndian = os.endianness() == 'BE'; - -// Find the next power-of-2 >= size -function nextPow2(size) { - return Math.pow(2, Math.ceil(Math.log(size) / Math.LN2)); -} - -// Expandable buffer that we can provide a size hint for -function Accumulator(initsize) { - this.buf = Buffer.alloc(nextPow2(initsize || 8192)); - this.readOffset = 0; - this.writeOffset = 0; -} -// For testing -exports.Accumulator = Accumulator - -// How much we can write into this buffer without allocating -Accumulator.prototype.writeAvail = function() { - return this.buf.length - this.writeOffset; -} - -// How much we can read -Accumulator.prototype.readAvail = function() { - return this.writeOffset - this.readOffset; -} - -// Ensure that we have enough space for size bytes -Accumulator.prototype.reserve = function(size) { - if (size < this.writeAvail()) { - return; - } - - // If we can make room by shunting down, do so - if (this.readOffset > 0) { - this.buf.copy(this.buf, 0, this.readOffset, this.writeOffset); - this.writeOffset -= this.readOffset; - this.readOffset = 0; - } - - // If we made enough room, no need to allocate more - if (size < this.writeAvail()) { - return; - } - - // Allocate a replacement and copy it in - var buf = Buffer.alloc(nextPow2(this.buf.length + size - this.writeAvail())); - this.buf.copy(buf); - this.buf = buf; -} - -// Append buffer or string. Will resize as needed -Accumulator.prototype.append = function(buf) { - if (Buffer.isBuffer(buf)) { - this.reserve(buf.length); - buf.copy(this.buf, this.writeOffset, 0, buf.length); - this.writeOffset += buf.length; - } else { - var size = Buffer.byteLength(buf); - this.reserve(size); - this.buf.write(buf, this.writeOffset); - this.writeOffset += size; - } -} - -Accumulator.prototype.assertReadableSize = function(size) { - if (this.readAvail() < size) { - throw new Error("wanted to read " + size + - " bytes but only have " + this.readAvail()); - } -} - -Accumulator.prototype.peekString = function(size) { - this.assertReadableSize(size); - return this.buf.toString('utf-8', this.readOffset, this.readOffset + size); -} - -Accumulator.prototype.readString = function(size) { - var str = this.peekString(size); - this.readOffset += size; - return str; -} - -Accumulator.prototype.peekInt = function(size) { - this.assertReadableSize(size); - switch (size) { - case 1: - return this.buf.readInt8(this.readOffset, size); - case 2: - return isBigEndian ? - this.buf.readInt16BE(this.readOffset, size) : - this.buf.readInt16LE(this.readOffset, size); - case 4: - return isBigEndian ? - this.buf.readInt32BE(this.readOffset, size) : - this.buf.readInt32LE(this.readOffset, size); - case 8: - var big = this.buf.slice(this.readOffset, this.readOffset + 8); - if (isBigEndian) { - // On a big endian system we can simply pass the buffer directly - return new Int64(big); - } - // Otherwise we need to byteswap - return new Int64(byteswap64(big)); - default: - throw new Error("invalid integer size " + size); - } -} - -Accumulator.prototype.readInt = function(bytes) { - var ival = this.peekInt(bytes); - if (ival instanceof Int64 && isFinite(ival.valueOf())) { - ival = ival.valueOf(); - } - this.readOffset += bytes; - return ival; -} - -Accumulator.prototype.peekDouble = function() { - this.assertReadableSize(8); - return isBigEndian ? - this.buf.readDoubleBE(this.readOffset) : - this.buf.readDoubleLE(this.readOffset); -} - -Accumulator.prototype.readDouble = function() { - var dval = this.peekDouble(); - this.readOffset += 8; - return dval; -} - -Accumulator.prototype.readAdvance = function(size) { - if (size > 0) { - this.assertReadableSize(size); - } else if (size < 0 && this.readOffset + size < 0) { - throw new Error("advance with negative offset " + size + - " would seek off the start of the buffer"); - } - this.readOffset += size; -} - -Accumulator.prototype.writeByte = function(value) { - this.reserve(1); - this.buf.writeInt8(value, this.writeOffset); - ++this.writeOffset; -} - -Accumulator.prototype.writeInt = function(value, size) { - this.reserve(size); - switch (size) { - case 1: - this.buf.writeInt8(value, this.writeOffset); - break; - case 2: - if (isBigEndian) { - this.buf.writeInt16BE(value, this.writeOffset); - } else { - this.buf.writeInt16LE(value, this.writeOffset); - } - break; - case 4: - if (isBigEndian) { - this.buf.writeInt32BE(value, this.writeOffset); - } else { - this.buf.writeInt32LE(value, this.writeOffset); - } - break; - default: - throw new Error("unsupported integer size " + size); - } - this.writeOffset += size; -} - -Accumulator.prototype.writeDouble = function(value) { - this.reserve(8); - if (isBigEndian) { - this.buf.writeDoubleBE(value, this.writeOffset); - } else { - this.buf.writeDoubleLE(value, this.writeOffset); - } - this.writeOffset += 8; -} - -var BSER_ARRAY = 0x00; -var BSER_OBJECT = 0x01; -var BSER_STRING = 0x02; -var BSER_INT8 = 0x03; -var BSER_INT16 = 0x04; -var BSER_INT32 = 0x05; -var BSER_INT64 = 0x06; -var BSER_REAL = 0x07; -var BSER_TRUE = 0x08; -var BSER_FALSE = 0x09; -var BSER_NULL = 0x0a; -var BSER_TEMPLATE = 0x0b; -var BSER_SKIP = 0x0c; - -var ST_NEED_PDU = 0; // Need to read and decode PDU length -var ST_FILL_PDU = 1; // Know the length, need to read whole content - -var MAX_INT8 = 127; -var MAX_INT16 = 32767; -var MAX_INT32 = 2147483647; - -function BunserBuf() { - EE.call(this); - this.buf = new Accumulator(); - this.state = ST_NEED_PDU; -} -util.inherits(BunserBuf, EE); -exports.BunserBuf = BunserBuf; - -BunserBuf.prototype.append = function(buf, synchronous) { - if (synchronous) { - this.buf.append(buf); - return this.process(synchronous); - } - - try { - this.buf.append(buf); - } catch (err) { - this.emit('error', err); - return; - } - // Arrange to decode later. This allows the consuming - // application to make progress with other work in the - // case that we have a lot of subscription updates coming - // in from a large tree. - this.processLater(); -} - -BunserBuf.prototype.processLater = function() { - var self = this; - process.nextTick(function() { - try { - self.process(false); - } catch (err) { - self.emit('error', err); - } - }); -} - -// Do something with the buffer to advance our state. -// If we're running synchronously we'll return either -// the value we've decoded or undefined if we don't -// yet have enought data. -// If we're running asynchronously, we'll emit the value -// when it becomes ready and schedule another invocation -// of process on the next tick if we still have data we -// can process. -BunserBuf.prototype.process = function(synchronous) { - if (this.state == ST_NEED_PDU) { - if (this.buf.readAvail() < 2) { - return; - } - // Validate BSER header - this.expectCode(0); - this.expectCode(1); - this.pduLen = this.decodeInt(true /* relaxed */); - if (this.pduLen === false) { - // Need more data, walk backwards - this.buf.readAdvance(-2); - return; - } - // Ensure that we have a big enough buffer to read the rest of the PDU - this.buf.reserve(this.pduLen); - this.state = ST_FILL_PDU; - } - - if (this.state == ST_FILL_PDU) { - if (this.buf.readAvail() < this.pduLen) { - // Need more data - return; - } - - // We have enough to decode it - var val = this.decodeAny(); - if (synchronous) { - return val; - } - this.emit('value', val); - this.state = ST_NEED_PDU; - } - - if (!synchronous && this.buf.readAvail() > 0) { - this.processLater(); - } -} - -BunserBuf.prototype.raise = function(reason) { - throw new Error(reason + ", in Buffer of length " + - this.buf.buf.length + " (" + this.buf.readAvail() + - " readable) at offset " + this.buf.readOffset + " buffer: " + - JSON.stringify(this.buf.buf.slice( - this.buf.readOffset, this.buf.readOffset + 32).toJSON())); -} - -BunserBuf.prototype.expectCode = function(expected) { - var code = this.buf.readInt(1); - if (code != expected) { - this.raise("expected bser opcode " + expected + " but got " + code); - } -} - -BunserBuf.prototype.decodeAny = function() { - var code = this.buf.peekInt(1); - switch (code) { - case BSER_INT8: - case BSER_INT16: - case BSER_INT32: - case BSER_INT64: - return this.decodeInt(); - case BSER_REAL: - this.buf.readAdvance(1); - return this.buf.readDouble(); - case BSER_TRUE: - this.buf.readAdvance(1); - return true; - case BSER_FALSE: - this.buf.readAdvance(1); - return false; - case BSER_NULL: - this.buf.readAdvance(1); - return null; - case BSER_STRING: - return this.decodeString(); - case BSER_ARRAY: - return this.decodeArray(); - case BSER_OBJECT: - return this.decodeObject(); - case BSER_TEMPLATE: - return this.decodeTemplate(); - default: - this.raise("unhandled bser opcode " + code); - } -} - -BunserBuf.prototype.decodeArray = function() { - this.expectCode(BSER_ARRAY); - var nitems = this.decodeInt(); - var arr = []; - for (var i = 0; i < nitems; ++i) { - arr.push(this.decodeAny()); - } - return arr; -} - -BunserBuf.prototype.decodeObject = function() { - this.expectCode(BSER_OBJECT); - var nitems = this.decodeInt(); - var res = {}; - for (var i = 0; i < nitems; ++i) { - var key = this.decodeString(); - var val = this.decodeAny(); - res[key] = val; - } - return res; -} - -BunserBuf.prototype.decodeTemplate = function() { - this.expectCode(BSER_TEMPLATE); - var keys = this.decodeArray(); - var nitems = this.decodeInt(); - var arr = []; - for (var i = 0; i < nitems; ++i) { - var obj = {}; - for (var keyidx = 0; keyidx < keys.length; ++keyidx) { - if (this.buf.peekInt(1) == BSER_SKIP) { - this.buf.readAdvance(1); - continue; - } - var val = this.decodeAny(); - obj[keys[keyidx]] = val; - } - arr.push(obj); - } - return arr; -} - -BunserBuf.prototype.decodeString = function() { - this.expectCode(BSER_STRING); - var len = this.decodeInt(); - return this.buf.readString(len); -} - -// This is unusual compared to the other decode functions in that -// we may not have enough data available to satisfy the read, and -// we don't want to throw. This is only true when we're reading -// the PDU length from the PDU header; we'll set relaxSizeAsserts -// in that case. -BunserBuf.prototype.decodeInt = function(relaxSizeAsserts) { - if (relaxSizeAsserts && (this.buf.readAvail() < 1)) { - return false; - } else { - this.buf.assertReadableSize(1); - } - var code = this.buf.peekInt(1); - var size = 0; - switch (code) { - case BSER_INT8: - size = 1; - break; - case BSER_INT16: - size = 2; - break; - case BSER_INT32: - size = 4; - break; - case BSER_INT64: - size = 8; - break; - default: - this.raise("invalid bser int encoding " + code); - } - - if (relaxSizeAsserts && (this.buf.readAvail() < 1 + size)) { - return false; - } - this.buf.readAdvance(1); - return this.buf.readInt(size); -} - -// synchronously BSER decode a string and return the value -function loadFromBuffer(input) { - var buf = new BunserBuf(); - var result = buf.append(input, true); - if (buf.buf.readAvail()) { - throw Error( - 'excess data found after input buffer, use BunserBuf instead'); - } - if (typeof result === 'undefined') { - throw Error( - 'no bser found in string and no error raised!?'); - } - return result; -} -exports.loadFromBuffer = loadFromBuffer - -// Byteswap an arbitrary buffer, flipping from one endian -// to the other, returning a new buffer with the resultant data -function byteswap64(buf) { - var swap = Buffer.alloc(buf.length); - for (var i = 0; i < buf.length; i++) { - swap[i] = buf[buf.length -1 - i]; - } - return swap; -} - -function dump_int64(buf, val) { - // Get the raw bytes. The Int64 buffer is big endian - var be = val.toBuffer(); - - if (isBigEndian) { - // We're a big endian system, so the buffer is exactly how we - // want it to be - buf.writeByte(BSER_INT64); - buf.append(be); - return; - } - // We need to byte swap to get the correct representation - var le = byteswap64(be); - buf.writeByte(BSER_INT64); - buf.append(le); -} - -function dump_int(buf, val) { - var abs = Math.abs(val); - if (abs <= MAX_INT8) { - buf.writeByte(BSER_INT8); - buf.writeInt(val, 1); - } else if (abs <= MAX_INT16) { - buf.writeByte(BSER_INT16); - buf.writeInt(val, 2); - } else if (abs <= MAX_INT32) { - buf.writeByte(BSER_INT32); - buf.writeInt(val, 4); - } else { - dump_int64(buf, new Int64(val)); - } -} - -function dump_any(buf, val) { - switch (typeof(val)) { - case 'number': - // check if it is an integer or a float - if (isFinite(val) && Math.floor(val) === val) { - dump_int(buf, val); - } else { - buf.writeByte(BSER_REAL); - buf.writeDouble(val); - } - return; - case 'string': - buf.writeByte(BSER_STRING); - dump_int(buf, Buffer.byteLength(val)); - buf.append(val); - return; - case 'boolean': - buf.writeByte(val ? BSER_TRUE : BSER_FALSE); - return; - case 'object': - if (val === null) { - buf.writeByte(BSER_NULL); - return; - } - if (val instanceof Int64) { - dump_int64(buf, val); - return; - } - if (Array.isArray(val)) { - buf.writeByte(BSER_ARRAY); - dump_int(buf, val.length); - for (var i = 0; i < val.length; ++i) { - dump_any(buf, val[i]); - } - return; - } - buf.writeByte(BSER_OBJECT); - var keys = Object.keys(val); - - // First pass to compute number of defined keys - var num_keys = keys.length; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var v = val[key]; - if (typeof(v) == 'undefined') { - num_keys--; - } - } - dump_int(buf, num_keys); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var v = val[key]; - if (typeof(v) == 'undefined') { - // Don't include it - continue; - } - dump_any(buf, key); - try { - dump_any(buf, v); - } catch (e) { - throw new Error( - e.message + ' (while serializing object property with name `' + - key + "')"); - } - } - return; - - default: - throw new Error('cannot serialize type ' + typeof(val) + ' to BSER'); - } -} - -// BSER encode value and return a buffer of the contents -function dumpToBuffer(val) { - var buf = new Accumulator(); - // Build out the header - buf.writeByte(0); - buf.writeByte(1); - // Reserve room for an int32 to hold our PDU length - buf.writeByte(BSER_INT32); - buf.writeInt(0, 4); // We'll come back and fill this in at the end - - dump_any(buf, val); - - // Compute PDU length - var off = buf.writeOffset; - var len = off - 7 /* the header length */; - buf.writeOffset = 3; // The length value to fill in - buf.writeInt(len, 4); // write the length in the space we reserved - buf.writeOffset = off; - - return buf.buf.slice(0, off); -} -exports.dumpToBuffer = dumpToBuffer - - -/***/ }), -/* 330 */ -/***/ (function(module, exports) { - -// Int64.js -// -// Copyright (c) 2012 Robert Kieffer -// MIT License - http://opensource.org/licenses/mit-license.php - -/** - * Support for handling 64-bit int numbers in Javascript (node.js) - * - * JS Numbers are IEEE-754 binary double-precision floats, which limits the - * range of values that can be represented with integer precision to: - * - * 2^^53 <= N <= 2^53 - * - * Int64 objects wrap a node Buffer that holds the 8-bytes of int64 data. These - * objects operate directly on the buffer which means that if they are created - * using an existing buffer then setting the value will modify the Buffer, and - * vice-versa. - * - * Internal Representation - * - * The internal buffer format is Big Endian. I.e. the most-significant byte is - * at buffer[0], the least-significant at buffer[7]. For the purposes of - * converting to/from JS native numbers, the value is assumed to be a signed - * integer stored in 2's complement form. - * - * For details about IEEE-754 see: - * http://en.wikipedia.org/wiki/Double_precision_floating-point_format - */ - -// Useful masks and values for bit twiddling -var MASK31 = 0x7fffffff, VAL31 = 0x80000000; -var MASK32 = 0xffffffff, VAL32 = 0x100000000; - -// Map for converting hex octets to strings -var _HEX = []; -for (var i = 0; i < 256; i++) { - _HEX[i] = (i > 0xF ? '' : '0') + i.toString(16); -} - -// -// Int64 -// - -/** - * Constructor accepts any of the following argument types: - * - * new Int64(buffer[, offset=0]) - Existing Buffer with byte offset - * new Int64(Uint8Array[, offset=0]) - Existing Uint8Array with a byte offset - * new Int64(string) - Hex string (throws if n is outside int64 range) - * new Int64(number) - Number (throws if n is outside int64 range) - * new Int64(hi, lo) - Raw bits as two 32-bit values - */ -var Int64 = module.exports = function(a1, a2) { - if (a1 instanceof Buffer) { - this.buffer = a1; - this.offset = a2 || 0; - } else if (Object.prototype.toString.call(a1) == '[object Uint8Array]') { - // Under Browserify, Buffers can extend Uint8Arrays rather than an - // instance of Buffer. We could assume the passed in Uint8Array is actually - // a buffer but that won't handle the case where a raw Uint8Array is passed - // in. We construct a new Buffer just in case. - this.buffer = new Buffer(a1); - this.offset = a2 || 0; - } else { - this.buffer = this.buffer || new Buffer(8); - this.offset = 0; - this.setValue.apply(this, arguments); - } -}; - - -// Max integer value that JS can accurately represent -Int64.MAX_INT = Math.pow(2, 53); - -// Min integer value that JS can accurately represent -Int64.MIN_INT = -Math.pow(2, 53); - -Int64.prototype = { - - constructor: Int64, - - /** - * Do in-place 2's compliment. See - * http://en.wikipedia.org/wiki/Two's_complement - */ - _2scomp: function() { - var b = this.buffer, o = this.offset, carry = 1; - for (var i = o + 7; i >= o; i--) { - var v = (b[i] ^ 0xff) + carry; - b[i] = v & 0xff; - carry = v >> 8; - } - }, - - /** - * Set the value. Takes any of the following arguments: - * - * setValue(string) - A hexidecimal string - * setValue(number) - Number (throws if n is outside int64 range) - * setValue(hi, lo) - Raw bits as two 32-bit values - */ - setValue: function(hi, lo) { - var negate = false; - if (arguments.length == 1) { - if (typeof(hi) == 'number') { - // Simplify bitfield retrieval by using abs() value. We restore sign - // later - negate = hi < 0; - hi = Math.abs(hi); - lo = hi % VAL32; - hi = hi / VAL32; - if (hi > VAL32) throw new RangeError(hi + ' is outside Int64 range'); - hi = hi | 0; - } else if (typeof(hi) == 'string') { - hi = (hi + '').replace(/^0x/, ''); - lo = hi.substr(-8); - hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : ''; - hi = parseInt(hi, 16); - lo = parseInt(lo, 16); - } else { - throw new Error(hi + ' must be a Number or String'); - } - } - - // Technically we should throw if hi or lo is outside int32 range here, but - // it's not worth the effort. Anything past the 32'nd bit is ignored. - - // Copy bytes to buffer - var b = this.buffer, o = this.offset; - for (var i = 7; i >= 0; i--) { - b[o+i] = lo & 0xff; - lo = i == 4 ? hi : lo >>> 8; - } - - // Restore sign of passed argument - if (negate) this._2scomp(); - }, - - /** - * Convert to a native JS number. - * - * WARNING: Do not expect this value to be accurate to integer precision for - * large (positive or negative) numbers! - * - * @param allowImprecise If true, no check is performed to verify the - * returned value is accurate to integer precision. If false, imprecise - * numbers (very large positive or negative numbers) will be forced to +/- - * Infinity. - */ - toNumber: function(allowImprecise) { - var b = this.buffer, o = this.offset; - - // Running sum of octets, doing a 2's complement - var negate = b[o] & 0x80, x = 0, carry = 1; - for (var i = 7, m = 1; i >= 0; i--, m *= 256) { - var v = b[o+i]; - - // 2's complement for negative numbers - if (negate) { - v = (v ^ 0xff) + carry; - carry = v >> 8; - v = v & 0xff; - } - - x += v * m; - } - - // Return Infinity if we've lost integer precision - if (!allowImprecise && x >= Int64.MAX_INT) { - return negate ? -Infinity : Infinity; - } - - return negate ? -x : x; - }, - - /** - * Convert to a JS Number. Returns +/-Infinity for values that can't be - * represented to integer precision. - */ - valueOf: function() { - return this.toNumber(false); - }, - - /** - * Return string value - * - * @param radix Just like Number#toString()'s radix - */ - toString: function(radix) { - return this.valueOf().toString(radix || 10); - }, - - /** - * Return a string showing the buffer octets, with MSB on the left. - * - * @param sep separator string. default is '' (empty string) - */ - toOctetString: function(sep) { - var out = new Array(8); - var b = this.buffer, o = this.offset; - for (var i = 0; i < 8; i++) { - out[i] = _HEX[b[o+i]]; - } - return out.join(sep || ''); - }, - - /** - * Returns the int64's 8 bytes in a buffer. - * - * @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if - * you're discarding the Int64 afterwards, as it breaks encapsulation. - */ - toBuffer: function(rawBuffer) { - if (rawBuffer && this.offset === 0) return this.buffer; - - var out = new Buffer(8); - this.buffer.copy(out, 0, this.offset, this.offset + 8); - return out; - }, - - /** - * Copy 8 bytes of int64 into target buffer at target offset. - * - * @param {Buffer} targetBuffer Buffer to copy into. - * @param {number} [targetOffset=0] Offset into target buffer. - */ - copy: function(targetBuffer, targetOffset) { - this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8); - }, - - /** - * Returns a number indicating whether this comes before or after or is the - * same as the other in sort order. - * - * @param {Int64} other Other Int64 to compare. - */ - compare: function(other) { - - // If sign bits differ ... - if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { - return other.buffer[other.offset] - this.buffer[this.offset]; - } - - // otherwise, compare bytes lexicographically - for (var i = 0; i < 8; i++) { - if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { - return this.buffer[this.offset+i] - other.buffer[other.offset+i]; - } - } - return 0; - }, - - /** - * Returns a boolean indicating if this integer is equal to other. - * - * @param {Int64} other Other Int64 to compare. - */ - equals: function(other) { - return this.compare(other) === 0; - }, - - /** - * Pretty output in console.log - */ - inspect: function() { - return '[Int64 value:' + this + ' octets:' + this.toOctetString(' ') + ']'; - } -}; - - -/***/ }), -/* 331 */ -/***/ (function(module) { - -module.exports = JSON.parse("{\"name\":\"coc.nvim\",\"version\":\"0.0.79\",\"description\":\"LSP based intellisense engine for neovim & vim8.\",\"main\":\"./lib/index.js\",\"engines\":{\"node\":\">=8.10.0\"},\"scripts\":{\"clean\":\"rimraf lib build\",\"lint\":\"eslint . --ext .ts --quiet\",\"build\":\"tsc -p tsconfig.json\",\"watch\":\"tsc -p tsconfig.json --watch true --sourceMap\",\"test\":\"node --trace-warnings node_modules/jest/bin/jest.js --runInBand --detectOpenHandles --forceExit\",\"test-build\":\"node --trace-warnings node_modules/jest/bin/jest.js --runInBand --coverage --forceExit\",\"prepare\":\"npm-run-all clean build\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/neoclide/coc.nvim.git\"},\"keywords\":[\"complete\",\"neovim\"],\"author\":\"Qiming Zhao \",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/neoclide/coc.nvim/issues\"},\"homepage\":\"https://github.com/neoclide/coc.nvim#readme\",\"jest\":{\"globals\":{\"__TEST__\":true},\"watchman\":false,\"clearMocks\":true,\"globalSetup\":\"./jest.js\",\"testEnvironment\":\"node\",\"moduleFileExtensions\":[\"ts\",\"tsx\",\"json\",\"js\"],\"transform\":{\"^.+\\\\.tsx?$\":\"ts-jest\"},\"testRegex\":\"src/__tests__/.*\\\\.(test|spec)\\\\.ts$\",\"coverageDirectory\":\"./coverage/\"},\"devDependencies\":{\"@types/debounce\":\"^3.0.0\",\"@types/fb-watchman\":\"^2.0.0\",\"@types/glob\":\"^7.1.3\",\"@types/jest\":\"^26.0.15\",\"@types/minimatch\":\"^3.0.3\",\"@types/mkdirp\":\"^1.0.1\",\"@types/node\":\"^10.12.0\",\"@types/semver\":\"^7.3.4\",\"@types/tar\":\"^4.0.3\",\"@types/uuid\":\"^8.3.0\",\"@types/which\":\"^1.3.2\",\"@typescript-eslint/eslint-plugin\":\"^4.6.0\",\"@typescript-eslint/eslint-plugin-tslint\":\"^4.6.0\",\"@typescript-eslint/parser\":\"^4.6.0\",\"colors\":\"^1.4.0\",\"eslint\":\"^7.12.1\",\"eslint-config-prettier\":\"^6.15.0\",\"eslint-plugin-jest\":\"^24.1.0\",\"eslint-plugin-jsdoc\":\"^30.7.3\",\"jest\":\"26.6.1\",\"npm-run-all\":\"^4.1.5\",\"prettier\":\"^2.1.2\",\"ts-jest\":\"^26.4.3\",\"typescript\":\"^4.0.5\",\"vscode-languageserver\":\"^6.1.1\"},\"dependencies\":{\"@chemzqm/neovim\":\"^5.2.8\",\"bser\":\"^2.1.1\",\"bytes\":\"^3.1.0\",\"clipboardy\":\"^2.3.0\",\"content-disposition\":\"^0.5.3\",\"debounce\":\"^1.2.0\",\"fast-diff\":\"^1.2.0\",\"fb-watchman\":\"^2.0.1\",\"follow-redirects\":\"^1.13.0\",\"glob\":\"^7.1.6\",\"http-proxy-agent\":\"^4.0.1\",\"https-proxy-agent\":\"^5.0.0\",\"isuri\":\"^2.0.3\",\"jsonc-parser\":\"^2.3.1\",\"log4js\":\"^6.3.0\",\"minimatch\":\"^3.0.4\",\"mkdirp\":\"^1.0.4\",\"mv\":\"^2.1.1\",\"promise.prototype.finally\":\"^3.1.2\",\"rc\":\"^1.2.8\",\"rimraf\":\"^3.0.2\",\"semver\":\"^7.3.2\",\"tar\":\"^6.0.5\",\"tslib\":\"^2.0.3\",\"unzipper\":\"^0.10.11\",\"uuid\":\"^7.0.3\",\"vscode-languageserver-protocol\":\"^3.15.3\",\"vscode-languageserver-textdocument\":\"^1.0.1\",\"vscode-languageserver-types\":\"^3.15.1\",\"vscode-uri\":\"^2.1.2\",\"which\":\"^2.0.2\"}}"); - -/***/ }), -/* 332 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.omit = exports.defaults = void 0; -/** Used for built-in method references. */ -const objectProto = Object.prototype; -/** Used to check objects for own properties. */ -const hasOwnProperty = objectProto.hasOwnProperty; -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @since 0.1.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see defaultsDeep - * @example - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }) - * // => { 'a': 1, 'b': 2 } - */ -function defaults(obj, ...sources) { - obj = Object(obj); - sources.forEach(source => { - if (source != null) { - source = Object(source); - for (const key in source) { - const value = obj[key]; - if (value === undefined || - (value === objectProto[key] && !hasOwnProperty.call(obj, key))) { - obj[key] = source[key]; - } - } - } - }); - return obj; -} -exports.defaults = defaults; -function omit(obj, properties) { - let o = {}; - for (let key of Object.keys(obj)) { - if (!properties.includes(key)) { - o[key] = obj[key]; - } - } - return o; -} -exports.omit = omit; -//# sourceMappingURL=lodash.js.map - -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.terminate = void 0; -const tslib_1 = __webpack_require__(65); -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -const cp = tslib_1.__importStar(__webpack_require__(239)); -const path_1 = __webpack_require__(82); -const isWebpack = typeof __webpack_require__ === "function"; -const isWindows = process.platform === 'win32'; -const isMacintosh = process.platform === 'darwin'; -const isLinux = process.platform === 'linux'; -const pluginRoot = isWebpack ? path_1.dirname(__dirname) : path_1.resolve(__dirname, '../..'); -function terminate(process, cwd) { - if (isWindows) { - try { - // This we run in Atom execFileSync is available. - // Ignore stderr since this is otherwise piped to parent.stderr - // which might be already closed. - let options = { - stdio: ['pipe', 'pipe', 'ignore'] - }; - if (cwd) { - options.cwd = cwd; - } - cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options); - return true; - } - catch (err) { - return false; - } - } - else if (isLinux || isMacintosh) { - try { - let cmd = path_1.join(pluginRoot, 'bin/terminateProcess.sh'); - let result = cp.spawnSync(cmd, [process.pid.toString()]); - return result.error ? false : true; - } - catch (err) { - return false; - } - } - else { - process.kill('SIGKILL'); - return true; - } -} -exports.terminate = terminate; -//# sourceMappingURL=processes.js.map - -/***/ }), -/* 334 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagnosticBuffer = void 0; -const tslib_1 = __webpack_require__(65); -const debounce_1 = tslib_1.__importDefault(__webpack_require__(240)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const util_1 = __webpack_require__(335); -const logger = __webpack_require__(64)('diagnostic-buffer'); -const severityNames = ['CocError', 'CocWarning', 'CocInfo', 'CocHint']; -// maintains sign and highlightId -class DiagnosticBuffer { - constructor(bufnr, uri, config) { - this.bufnr = bufnr; - this.uri = uri; - this.config = config; - this.signIds = new Set(); - this._onDidRefresh = new vscode_languageserver_protocol_1.Emitter(); - this.matchIds = new Set(); - this.onDidRefresh = this._onDidRefresh.event; - this.srdId = workspace_1.default.createNameSpace('coc-diagnostic'); - this.refresh = debounce_1.default((diagnostics) => { - this._refresh(diagnostics).logError(); - }, 300); - } - /** - * Refresh diagnostics without debounce - */ - forceRefresh(diagnostics) { - this.refresh.clear(); - this._refresh(diagnostics).logError(); - } - async _refresh(diagnostics) { - let { refreshOnInsertMode } = this.config; - let { nvim } = this; - let arr = await nvim.eval(`[coc#util#check_refresh(${this.bufnr}),mode(),bufnr("%"),line("."),getloclist(bufwinid(${this.bufnr}),{'title':1})]`); - if (arr[0] == 0) - return; - let mode = arr[1]; - if (!refreshOnInsertMode && mode.startsWith('i') && diagnostics.length) - return; - let bufnr = arr[2]; - let lnum = arr[3]; - nvim.pauseNotification(); - this.setDiagnosticInfo(diagnostics); - this.addSigns(diagnostics); - this.addHighlight(diagnostics, bufnr); - this.updateLocationList(arr[4], diagnostics); - if (this.bufnr == bufnr) { - this.showVirtualText(diagnostics, lnum); - } - if (workspace_1.default.isVim) { - this.nvim.command('redraw', true); - } - let res = await this.nvim.resumeNotification(); - if (Array.isArray(res) && res[1]) - throw new Error(res[1]); - this._onDidRefresh.fire(void 0); - } - clearSigns() { - let { nvim, signIds, bufnr } = this; - if (signIds.size > 0) { - nvim.call('coc#util#unplace_signs', [bufnr, Array.from(signIds)], true); - signIds.clear(); - } - } - async checkSigns() { - let { nvim, bufnr, signIds } = this; - try { - let content = await this.nvim.call('execute', [`sign place buffer=${bufnr}`]); - let lines = content.split('\n'); - let ids = []; - for (let line of lines) { - let ms = line.match(/^\s*line=\d+\s+id=(\d+)\s+name=(\w+)/); - if (!ms) - continue; - let [, id, name] = ms; - if (!signIds.has(Number(id)) && severityNames.includes(name)) { - ids.push(id); - } - } - await nvim.call('coc#util#unplace_signs', [bufnr, ids]); - } - catch (e) { - // noop - } - } - updateLocationList(curr, diagnostics) { - if (!this.config.locationlistUpdate) - return; - if (!curr || curr.title !== 'Diagnostics of coc') - return; - let items = []; - for (let diagnostic of diagnostics) { - let item = util_1.getLocationListItem(this.bufnr, diagnostic); - items.push(item); - } - this.nvim.call('setloclist', [0, [], 'r', { title: 'Diagnostics of coc', items }], true); - } - addSigns(diagnostics) { - if (!this.config.enableSign) - return; - this.clearSigns(); - let { nvim, bufnr, signIds } = this; - let signId = this.config.signOffset; - let lines = new Set(); - for (let diagnostic of diagnostics) { - let { range, severity } = diagnostic; - let line = range.start.line; - if (lines.has(line)) - continue; - lines.add(line); - let name = util_1.getNameFromSeverity(severity); - nvim.command(`sign place ${signId} line=${line + 1} name=${name} buffer=${bufnr}`, true); - signIds.add(signId); - signId = signId + 1; - } - } - setDiagnosticInfo(diagnostics) { - let lnums = [0, 0, 0, 0]; - let info = { error: 0, warning: 0, information: 0, hint: 0, lnums }; - for (let diagnostic of diagnostics) { - switch (diagnostic.severity) { - case vscode_languageserver_protocol_1.DiagnosticSeverity.Warning: - info.warning = info.warning + 1; - lnums[1] = lnums[1] || diagnostic.range.start.line + 1; - break; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Information: - info.information = info.information + 1; - lnums[2] = lnums[2] || diagnostic.range.start.line + 1; - break; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Hint: - info.hint = info.hint + 1; - lnums[3] = lnums[3] || diagnostic.range.start.line + 1; - break; - default: - lnums[0] = lnums[0] || diagnostic.range.start.line + 1; - info.error = info.error + 1; - } - } - this.nvim.call('coc#util#set_buf_var', [this.bufnr, 'coc_diagnostic_info', info], true); - this.nvim.call('coc#util#do_autocmd', ['CocDiagnosticChange'], true); - } - showVirtualText(diagnostics, lnum) { - let { bufnr, config } = this; - if (!config.virtualText) - return; - let buffer = this.nvim.createBuffer(bufnr); - let srcId = this.config.virtualTextSrcId; - let prefix = this.config.virtualTextPrefix; - if (this.config.virtualTextCurrentLineOnly) { - diagnostics = diagnostics.filter(d => { - let { start, end } = d.range; - return start.line <= lnum - 1 && end.line >= lnum - 1; - }); - } - buffer.clearNamespace(srcId); - for (let diagnostic of diagnostics) { - let { line } = diagnostic.range.start; - let highlight = util_1.getNameFromSeverity(diagnostic.severity) + 'VirtualText'; - let msg = diagnostic.message.split(/\n/) - .map((l) => l.trim()) - .filter((l) => l.length > 0) - .slice(0, this.config.virtualTextLines) - .join(this.config.virtualTextLineSeparator); - buffer.setVirtualText(srcId, line, [[prefix + msg, highlight]], {}).logError(); - } - } - clearHighlight() { - let { matchIds, document } = this; - if (document) { - document.clearMatchIds(matchIds); - } - this.matchIds.clear(); - } - addHighlight(diagnostics, bufnr) { - this.clearHighlight(); - if (diagnostics.length == 0) - return; - // can't add highlight for old vim - if (workspace_1.default.isVim && !workspace_1.default.env.textprop && bufnr != this.bufnr) - return; - let { document } = this; - if (!document) - return; - // TODO support DiagnosticTag - const highlights = new Map(); - for (let diagnostic of diagnostics) { - let { range, severity } = diagnostic; - let hlGroup = util_1.getNameFromSeverity(severity) + 'Highlight'; - let ranges = highlights.get(hlGroup) || []; - ranges.push(range); - highlights.set(hlGroup, ranges); - } - for (let [hlGroup, ranges] of highlights.entries()) { - let matchIds = document.highlightRanges(ranges, hlGroup, this.srdId); - for (let id of matchIds) - this.matchIds.add(id); - } - } - /** - * Used on buffer unload - * - * @public - * @returns {Promise} - */ - async clear() { - this.refresh.clear(); - let { nvim } = this; - nvim.pauseNotification(); - this.clearHighlight(); - this.clearSigns(); - if (this.config.virtualText) { - let buffer = nvim.createBuffer(this.bufnr); - buffer.clearNamespace(this.config.virtualTextSrcId); - } - this.setDiagnosticInfo([]); - await nvim.resumeNotification(false, true); - } - hasHighlights() { - return this.matchIds.size > 0; - } - dispose() { - this.refresh.clear(); - this._onDidRefresh.dispose(); - } - get document() { - return workspace_1.default.getDocument(this.uri); - } - get nvim() { - return workspace_1.default.nvim; - } -} -exports.DiagnosticBuffer = DiagnosticBuffer; -//# sourceMappingURL=buffer.js.map - -/***/ }), -/* 335 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getLocationListItem = exports.getNameFromSeverity = exports.severityLevel = exports.getSeverityType = exports.getSeverityName = void 0; -const vscode_languageserver_protocol_1 = __webpack_require__(211); -function getSeverityName(severity) { - switch (severity) { - case vscode_languageserver_protocol_1.DiagnosticSeverity.Error: - return 'Error'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Warning: - return 'Warning'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Information: - return 'Information'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Hint: - return 'Hint'; - default: - return 'Error'; - } -} -exports.getSeverityName = getSeverityName; -function getSeverityType(severity) { - switch (severity) { - case vscode_languageserver_protocol_1.DiagnosticSeverity.Error: - return 'E'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Warning: - return 'W'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Information: - return 'I'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Hint: - return 'I'; - default: - return 'Error'; - } -} -exports.getSeverityType = getSeverityType; -function severityLevel(level) { - switch (level) { - case 'hint': - return vscode_languageserver_protocol_1.DiagnosticSeverity.Hint; - case 'information': - return vscode_languageserver_protocol_1.DiagnosticSeverity.Information; - case 'warning': - return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning; - case 'error': - return vscode_languageserver_protocol_1.DiagnosticSeverity.Error; - default: - return vscode_languageserver_protocol_1.DiagnosticSeverity.Hint; - } -} -exports.severityLevel = severityLevel; -function getNameFromSeverity(severity) { - switch (severity) { - case vscode_languageserver_protocol_1.DiagnosticSeverity.Error: - return 'CocError'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Warning: - return 'CocWarning'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Information: - return 'CocInfo'; - case vscode_languageserver_protocol_1.DiagnosticSeverity.Hint: - return 'CocHint'; - default: - return 'CocError'; - } -} -exports.getNameFromSeverity = getNameFromSeverity; -function getLocationListItem(bufnr, diagnostic) { - let { start } = diagnostic.range; - let owner = diagnostic.source || 'coc.nvim'; - let msg = diagnostic.message.split('\n')[0]; - let type = getSeverityName(diagnostic.severity).slice(0, 1).toUpperCase(); - return { - bufnr, - lnum: start.line + 1, - col: start.character + 1, - text: `[${owner}${diagnostic.code ? ' ' + diagnostic.code : ''}] ${msg} [${type}]`, - type - }; -} -exports.getLocationListItem = getLocationListItem; -//# sourceMappingURL=util.js.map - -/***/ }), -/* 336 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const position_1 = __webpack_require__(315); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const logger = __webpack_require__(64)('diagnostic-collection'); -class Collection { - constructor(owner) { - this.diagnosticsMap = new Map(); - this._onDispose = new vscode_languageserver_protocol_1.Emitter(); - this._onDidDiagnosticsChange = new vscode_languageserver_protocol_1.Emitter(); - this._onDidDiagnosticsClear = new vscode_languageserver_protocol_1.Emitter(); - this.onDispose = this._onDispose.event; - this.onDidDiagnosticsChange = this._onDidDiagnosticsChange.event; - this.onDidDiagnosticsClear = this._onDidDiagnosticsClear.event; - this.name = owner; - } - set(entries, diagnostics) { - if (!Array.isArray(entries)) { - let uri = entries; - // if called as set(uri, diagnostics) - // -> convert into single-entry entries list - entries = [[uri, diagnostics]]; - } - let diagnosticsPerFile = new Map(); - for (let item of entries) { - let [file, diagnostics] = item; - if (diagnostics == null) { - // clear diagnostics if entry contains null - diagnostics = []; - } - else { - diagnostics = (diagnosticsPerFile.get(file) || []).concat(diagnostics); - } - diagnosticsPerFile.set(file, diagnostics); - } - for (let item of diagnosticsPerFile) { - let [uri, diagnostics] = item; - uri = vscode_uri_1.URI.parse(uri).toString(); - diagnostics.forEach(o => { - o.range = o.range || vscode_languageserver_protocol_1.Range.create(0, 0, 1, 0); - o.message = o.message || 'Empty error message'; - if (position_1.emptyRange(o.range)) { - o.range.end = { - line: o.range.end.line, - character: o.range.end.character + 1 - }; - } - let { start, end } = o.range; - // fix empty diagnostic at the and of line - if (end.character == 0 && end.line - start.line == 1 && start.character > 0) { - // add last character when start character is end - let doc = workspace_1.default.getDocument(uri); - if (doc) { - let line = doc.getline(start.line); - if (start.character == line.length) { - o.range.start.character = start.character - 1; - } - } - } - o.source = o.source || this.name; - }); - this.diagnosticsMap.set(uri, diagnostics); - this._onDidDiagnosticsChange.fire(uri); - } - return; - } - delete(uri) { - this.diagnosticsMap.delete(uri); - } - clear() { - let uris = Array.from(this.diagnosticsMap.keys()); - this.diagnosticsMap.clear(); - this._onDidDiagnosticsClear.fire(uris); - } - forEach(callback, thisArg) { - for (let uri of this.diagnosticsMap.keys()) { - let diagnostics = this.diagnosticsMap.get(uri); - callback.call(thisArg, uri, diagnostics, this); - } - } - get(uri) { - let arr = this.diagnosticsMap.get(uri); - return arr == null ? [] : arr; - } - has(uri) { - return this.diagnosticsMap.has(uri); - } - dispose() { - this.clear(); - this._onDispose.fire(void 0); - this._onDispose.dispose(); - this._onDidDiagnosticsClear.dispose(); - this._onDidDiagnosticsChange.dispose(); - } -} -exports.default = Collection; -//# sourceMappingURL=collection.js.map - -/***/ }), -/* 337 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SnippetManager = void 0; -const tslib_1 = __webpack_require__(65); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const Snippets = tslib_1.__importStar(__webpack_require__(338)); -const session_1 = __webpack_require__(339); -const variableResolve_1 = __webpack_require__(614); -const logger = __webpack_require__(64)('snippets-manager'); -class SnippetManager { - constructor() { - this.sessionMap = new Map(); - this.disposables = []; - workspace_1.default.onDidChangeTextDocument(async (e) => { - let session = this.getSession(e.bufnr); - if (session) { - await session.synchronizeUpdatedPlaceholders(e.contentChanges[0]); - } - }, null, this.disposables); - workspace_1.default.onDidCloseTextDocument(textDocument => { - let doc = workspace_1.default.getDocument(textDocument.uri); - if (!doc) - return; - let session = this.getSession(doc.bufnr); - if (session) - session.deactivate(); - }, null, this.disposables); - events_1.default.on('BufEnter', async (bufnr) => { - let session = this.getSession(bufnr); - if (!this.statusItem) - return; - if (session && session.isActive) { - this.statusItem.show(); - } - else { - this.statusItem.hide(); - } - }, null, this.disposables); - events_1.default.on('InsertEnter', async () => { - let { session } = this; - if (!session) - return; - await session.checkPosition(); - }, null, this.disposables); - } - init() { - let config = workspace_1.default.getConfiguration('coc.preferences'); - this.statusItem = workspace_1.default.createStatusBarItem(0); - this.statusItem.text = config.get('snippetStatusText', 'SNIP'); - } - /** - * Insert snippet at current cursor position - */ - async insertSnippet(snippet, select = true, range) { - let { bufnr } = workspace_1.default; - let session = this.getSession(bufnr); - if (!session) { - session = new session_1.SnippetSession(workspace_1.default.nvim, bufnr); - this.sessionMap.set(bufnr, session); - session.onCancel(() => { - this.sessionMap.delete(bufnr); - if (workspace_1.default.bufnr == bufnr) { - this.statusItem.hide(); - } - }); - } - let isActive = await session.start(snippet, select, range); - if (isActive) - this.statusItem.show(); - return isActive; - } - async selectCurrentPlaceholder(triggerAutocmd = true) { - let { session } = this; - if (session) - return await session.selectCurrentPlaceholder(triggerAutocmd); - } - async nextPlaceholder() { - let { session } = this; - if (session) - return await session.nextPlaceholder(); - workspace_1.default.nvim.call('coc#snippet#disable', [], true); - this.statusItem.hide(); - } - async previousPlaceholder() { - let { session } = this; - if (session) - return await session.previousPlaceholder(); - workspace_1.default.nvim.call('coc#snippet#disable', [], true); - this.statusItem.hide(); - } - cancel() { - let session = this.getSession(workspace_1.default.bufnr); - if (session) - return session.deactivate(); - workspace_1.default.nvim.call('coc#snippet#disable', [], true); - if (this.statusItem) - this.statusItem.hide(); - } - get session() { - let session = this.getSession(workspace_1.default.bufnr); - return session && session.isActive ? session : null; - } - isActived(bufnr) { - let session = this.getSession(bufnr); - return session && session.isActive; - } - jumpable() { - let { session } = this; - if (!session) - return false; - let placeholder = session.placeholder; - if (placeholder && !placeholder.isFinalTabstop) { - return true; - } - return false; - } - getSession(bufnr) { - return this.sessionMap.get(bufnr); - } - async resolveSnippet(body) { - let parser = new Snippets.SnippetParser(); - const snippet = parser.parse(body, true); - const resolver = new variableResolve_1.SnippetVariableResolver(); - snippet.resolveVariables(resolver); - return snippet; - } - dispose() { - this.cancel(); - for (let d of this.disposables) { - d.dispose(); - } - } -} -exports.SnippetManager = SnippetManager; -exports.default = new SnippetManager(); -//# sourceMappingURL=manager.js.map - -/***/ }), -/* 338 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SnippetParser = exports.TextmateSnippet = exports.Variable = exports.FormatString = exports.Transform = exports.Choice = exports.Placeholder = exports.TransformableMarker = exports.Text = exports.Marker = exports.Scanner = void 0; -const vscode_languageserver_textdocument_1 = __webpack_require__(295); -const logger = __webpack_require__(64)('snippets-parser'); -class Scanner { - constructor() { - this.text(''); - } - static isDigitCharacter(ch) { - return ch >= 48 /* Digit0 */ && ch <= 57 /* Digit9 */; - } - static isVariableCharacter(ch) { - return ch === 95 /* Underline */ - || (ch >= 97 /* a */ && ch <= 122 /* z */) - || (ch >= 65 /* A */ && ch <= 90 /* Z */); - } - text(value) { - this.value = value; - this.pos = 0; - } - tokenText(token) { - return this.value.substr(token.pos, token.len); - } - next() { - if (this.pos >= this.value.length) { - return { type: 14 /* EOF */, pos: this.pos, len: 0 }; - } - let pos = this.pos; - let len = 0; - let ch = this.value.charCodeAt(pos); - let type; - // static types - type = Scanner._table[ch]; - if (typeof type === 'number') { - this.pos += 1; - return { type, pos, len: 1 }; - } - // number - if (Scanner.isDigitCharacter(ch)) { - type = 8 /* Int */; - do { - len += 1; - ch = this.value.charCodeAt(pos + len); - } while (Scanner.isDigitCharacter(ch)); - this.pos += len; - return { type, pos, len }; - } - // variable name - if (Scanner.isVariableCharacter(ch)) { - type = 9 /* VariableName */; - do { - ch = this.value.charCodeAt(pos + (++len)); - } while (Scanner.isVariableCharacter(ch) || Scanner.isDigitCharacter(ch)); - this.pos += len; - return { type, pos, len }; - } - // format - type = 10 /* Format */; - do { - len += 1; - ch = this.value.charCodeAt(pos + len); - } while (!isNaN(ch) - && typeof Scanner._table[ch] === 'undefined' // not static token - && !Scanner.isDigitCharacter(ch) // not number - && !Scanner.isVariableCharacter(ch) // not variable - ); - this.pos += len; - return { type, pos, len }; - } -} -exports.Scanner = Scanner; -Scanner._table = { - [36 /* DollarSign */]: 0 /* Dollar */, - [58 /* Colon */]: 1 /* Colon */, - [44 /* Comma */]: 2 /* Comma */, - [123 /* OpenCurlyBrace */]: 3 /* CurlyOpen */, - [125 /* CloseCurlyBrace */]: 4 /* CurlyClose */, - [92 /* Backslash */]: 5 /* Backslash */, - [47 /* Slash */]: 6 /* Forwardslash */, - [124 /* Pipe */]: 7 /* Pipe */, - [43 /* Plus */]: 11 /* Plus */, - [45 /* Dash */]: 12 /* Dash */, - [63 /* QuestionMark */]: 13 /* QuestionMark */, -}; -class Marker { - constructor() { - this._children = []; - } - appendChild(child) { - if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) { - // this and previous child are text -> merge them - this._children[this._children.length - 1].value += child.value; - } - else { - // normal adoption of child - child.parent = this; - this._children.push(child); - } - return this; - } - setOnlyChild(child) { - child.parent = this; - this._children = [child]; - } - replace(child, others) { - const { parent } = child; - const idx = parent.children.indexOf(child); - const newChildren = parent.children.slice(0); - newChildren.splice(idx, 1, ...others); - parent._children = newChildren; - (function _fixParent(children, parent) { - for (const child of children) { - child.parent = parent; - _fixParent(child.children, child); - } - })(others, parent); - } - get children() { - return this._children; - } - get snippet() { - // eslint-disable-next-line @typescript-eslint/no-this-alias - let candidate = this; - // eslint-disable-next-line no-constant-condition - while (true) { - if (!candidate) { - return undefined; - } - if (candidate instanceof TextmateSnippet) { - return candidate; - } - candidate = candidate.parent; - } - } - toString() { - return this.children.reduce((prev, cur) => prev + cur.toString(), ''); - } - len() { - return 0; - } - get next() { - let { parent } = this; - let { children } = parent; - let idx = children.indexOf(this); - return children[idx + 1]; - } -} -exports.Marker = Marker; -class Text extends Marker { - constructor(value) { - super(); - this.value = value; - } - static escape(value) { - return value.replace(/\$|}|\\/g, '\\$&'); - } - toString() { - return this.value; - } - toTextmateString() { - return Text.escape(this.value); - } - len() { - return this.value.length; - } - clone() { - return new Text(this.value); - } -} -exports.Text = Text; -class TransformableMarker extends Marker { -} -exports.TransformableMarker = TransformableMarker; -class Placeholder extends TransformableMarker { - constructor(index) { - super(); - this.index = index; - } - static compareByIndex(a, b) { - if (a.index === b.index) { - return 0; - } - else if (a.isFinalTabstop) { - return 1; - } - else if (b.isFinalTabstop) { - return -1; - } - else if (a.index < b.index) { - return -1; - } - else if (a.index > b.index) { - return 1; - } - else { - return 0; - } - } - get isFinalTabstop() { - return this.index === 0; - } - get choice() { - return this._children.length === 1 && this._children[0] instanceof Choice - ? this._children[0] - : undefined; - } - toTextmateString() { - let transformString = ''; - if (this.transform) { - transformString = this.transform.toTextmateString(); - } - if (this.children.length === 0 && !this.transform) { - return `$${this.index}`; - } - else if (this.children.length === 0) { - return `\${${this.index}${transformString}}`; - } - else if (this.choice) { - return `\${${this.index}|${this.choice.toTextmateString()}|${transformString}}`; - } - else { - return `\${${this.index}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}`; - } - } - clone() { - let ret = new Placeholder(this.index); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map(child => child.clone()); - return ret; - } -} -exports.Placeholder = Placeholder; -class Choice extends Marker { - constructor() { - super(...arguments); - this.options = []; - } - appendChild(marker) { - if (marker instanceof Text) { - marker.parent = this; - this.options.push(marker); - } - return this; - } - toString() { - return this.options[0].value; - } - toTextmateString() { - return this.options - .map(option => option.value.replace(/\||,/g, '\\$&')) - .join(','); - } - len() { - return this.options[0].len(); - } - clone() { - let ret = new Choice(); - for (let opt of this.options) { - ret.appendChild(opt); - } - return ret; - } -} -exports.Choice = Choice; -class Transform extends Marker { - resolve(value) { - let didMatch = false; - let ret = value.replace(this.regexp, (...args) => { - didMatch = true; - return this._replace(args.slice(0, -2)); - }); - // when the regex didn't match and when the transform has - // else branches, then run those - if (!didMatch && this._children.some(child => child instanceof FormatString && Boolean(child.elseValue))) { - ret = this._replace([]); - } - return ret; - } - _replace(groups) { - let ret = ''; - for (const marker of this._children) { - if (marker instanceof FormatString) { - let value = groups[marker.index] || ''; - value = marker.resolve(value); - ret += value; - } - else { - ret += marker.toString(); - } - } - return ret; - } - toString() { - return ''; - } - toTextmateString() { - return `/${this.regexp.source}/${this.children.map(c => c.toTextmateString())}/${(this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')}`; - } - clone() { - let ret = new Transform(); - ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')); - ret._children = this.children.map(child => child.clone()); - return ret; - } -} -exports.Transform = Transform; -class FormatString extends Marker { - constructor(index, shorthandName, ifValue, elseValue) { - super(); - this.index = index; - this.shorthandName = shorthandName; - this.ifValue = ifValue; - this.elseValue = elseValue; - } - resolve(value) { - if (this.shorthandName === 'upcase') { - return !value ? '' : value.toLocaleUpperCase(); - } - else if (this.shorthandName === 'downcase') { - return !value ? '' : value.toLocaleLowerCase(); - } - else if (this.shorthandName === 'capitalize') { - return !value ? '' : (value[0].toLocaleUpperCase() + value.substr(1)); - } - else if (this.shorthandName === 'pascalcase') { - return !value ? '' : this._toPascalCase(value); - } - else if (Boolean(value) && typeof this.ifValue === 'string') { - return this.ifValue; - } - else if (!value && typeof this.elseValue === 'string') { - return this.elseValue; - } - else { - return value || ''; - } - } - _toPascalCase(value) { - const match = value.match(/[a-z]+/gi); - if (!match) { - return value; - } - return match.map(word => word.charAt(0).toUpperCase() - + word.substr(1).toLowerCase()) - .join(''); - } - toTextmateString() { - let value = '${'; - value += this.index; - if (this.shorthandName) { - value += `:/${this.shorthandName}`; - } - else if (this.ifValue && this.elseValue) { - value += `:?${this.ifValue}:${this.elseValue}`; - } - else if (this.ifValue) { - value += `:+${this.ifValue}`; - } - else if (this.elseValue) { - value += `:-${this.elseValue}`; - } - value += '}'; - return value; - } - clone() { - let ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue); - return ret; - } -} -exports.FormatString = FormatString; -class Variable extends TransformableMarker { - constructor(name) { - super(); - this.name = name; - } - resolve(resolver) { - let value = resolver.resolve(this); - if (value && value.includes('\n')) { - // get indent of previous Text child - let { children } = this.parent; - let idx = children.indexOf(this); - let previous = children[idx - 1]; - if (previous && previous instanceof Text) { - let ms = previous.value.match(/\n([ \t]*)$/); - if (ms) { - let lines = value.split('\n'); - let indents = lines.filter(s => s.length > 0).map(s => s.match(/^\s*/)[0]); - let minIndent = indents.length == 0 ? '' : - indents.reduce((p, c) => p.length < c.length ? p : c); - let newLines = lines.map((s, i) => i == 0 || s.length == 0 || !s.startsWith(minIndent) ? s : - ms[1] + s.slice(minIndent.length)); - value = newLines.join('\n'); - } - } - } - if (this.transform) { - value = this.transform.resolve(value || ''); - } - if (value !== undefined) { - this._children = [new Text(value)]; - return true; - } - return false; - } - toTextmateString() { - let transformString = ''; - if (this.transform) { - transformString = this.transform.toTextmateString(); - } - if (this.children.length === 0) { - return `\${${this.name}${transformString}}`; - } - else { - return `\${${this.name}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}`; - } - } - clone() { - const ret = new Variable(this.name); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map(child => child.clone()); - return ret; - } -} -exports.Variable = Variable; -function walk(marker, visitor) { - const stack = [...marker]; - while (stack.length > 0) { - const marker = stack.shift(); - const recurse = visitor(marker); - if (!recurse) { - break; - } - stack.unshift(...marker.children); - } -} -class TextmateSnippet extends Marker { - get placeholderInfo() { - if (!this._placeholders) { - this._variables = []; - // fill in placeholders - let all = []; - let last; - this.walk(candidate => { - if (candidate instanceof Placeholder) { - all.push(candidate); - last = !last || last.index < candidate.index ? candidate : last; - } - else if (candidate instanceof Variable) { - let first = candidate.name.charCodeAt(0); - // not jumpover for uppercase variable. - if (first < 65 || first > 90) { - this._variables.push(candidate); - } - } - return true; - }); - this._placeholders = { all, last }; - } - return this._placeholders; - } - get variables() { - return this._variables; - } - get placeholders() { - const { all } = this.placeholderInfo; - return all; - } - get maxIndexNumber() { - let { placeholders } = this; - return placeholders.reduce((curr, p) => Math.max(curr, p.index), 0); - } - get minIndexNumber() { - let { placeholders } = this; - let nums = placeholders.map(p => p.index); - nums.sort((a, b) => a - b); - if (nums.length > 1 && nums[0] == 0) - return nums[1]; - return nums[0] || 0; - } - insertSnippet(snippet, id, range) { - let placeholder = this.placeholders[id]; - if (!placeholder) - return; - let { index } = placeholder; - const document = vscode_languageserver_textdocument_1.TextDocument.create('untitled:/1', 'snippet', 0, placeholder.toString()); - snippet = vscode_languageserver_textdocument_1.TextDocument.applyEdits(document, [{ range, newText: snippet }]); - let nested = new SnippetParser().parse(snippet, true); - let maxIndexAdded = nested.maxIndexNumber + 1; - let indexes = []; - for (let p of nested.placeholders) { - if (p.isFinalTabstop) { - p.index = maxIndexAdded + index; - } - else { - p.index = p.index + index; - } - indexes.push(p.index); - } - this.walk(m => { - if (m instanceof Placeholder && m.index > index) { - m.index = m.index + maxIndexAdded; - } - return true; - }); - this.replace(placeholder, nested.children); - return Math.min.apply(null, indexes); - } - updatePlaceholder(id, val) { - const placeholder = this.placeholders[id]; - for (let p of this.placeholders) { - if (p.index == placeholder.index) { - let child = p.children[0]; - let newText = p.transform ? p.transform.resolve(val) : val; - if (child) { - p.setOnlyChild(new Text(newText)); - } - else { - p.appendChild(new Text(newText)); - } - } - } - this._placeholders = undefined; - } - updateVariable(id, val) { - const find = this.variables[id - this.maxIndexNumber - 1]; - if (find) { - let variables = this.variables.filter(o => o.name == find.name); - for (let variable of variables) { - let newText = variable.transform ? variable.transform.resolve(val) : val; - variable.setOnlyChild(new Text(newText)); - } - } - } - /** - * newText after update with value - */ - getPlaceholderText(id, value) { - const placeholder = this.placeholders[id]; - if (!placeholder) - return value; - return placeholder.transform ? placeholder.transform.resolve(value) : value; - } - offset(marker) { - let pos = 0; - let found = false; - this.walk(candidate => { - if (candidate === marker) { - found = true; - return false; - } - pos += candidate.len(); - return true; - }); - if (!found) { - return -1; - } - return pos; - } - fullLen(marker) { - let ret = 0; - walk([marker], marker => { - ret += marker.len(); - return true; - }); - return ret; - } - enclosingPlaceholders(placeholder) { - let ret = []; - let { parent } = placeholder; - while (parent) { - if (parent instanceof Placeholder) { - ret.push(parent); - } - parent = parent.parent; - } - return ret; - } - resolveVariables(resolver) { - this.walk(candidate => { - if (candidate instanceof Variable) { - if (candidate.resolve(resolver)) { - this._placeholders = undefined; - } - } - return true; - }); - return this; - } - appendChild(child) { - this._placeholders = undefined; - return super.appendChild(child); - } - replace(child, others) { - this._placeholders = undefined; - return super.replace(child, others); - } - toTextmateString() { - return this.children.reduce((prev, cur) => prev + cur.toTextmateString(), ''); - } - clone() { - let ret = new TextmateSnippet(); - this._children = this.children.map(child => child.clone()); - return ret; - } - walk(visitor) { - walk(this.children, visitor); - } -} -exports.TextmateSnippet = TextmateSnippet; -class SnippetParser { - constructor() { - this._scanner = new Scanner(); - } - static escape(value) { - return value.replace(/\$|}|\\/g, '\\$&'); - } - text(value) { - return this.parse(value).toString(); - } - parse(value, insertFinalTabstop) { - this._scanner.text(value); - this._token = this._scanner.next(); - const snippet = new TextmateSnippet(); - while (this._parse(snippet)) { - // nothing - } - // fill in values for placeholders. the first placeholder of an index - // that has a value defines the value for all placeholders with that index - const placeholderDefaultValues = new Map(); - const incompletePlaceholders = []; - snippet.walk(marker => { - if (marker instanceof Placeholder) { - if (marker.isFinalTabstop) { - placeholderDefaultValues.set(0, undefined); - } - else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) { - placeholderDefaultValues.set(marker.index, marker.children); - } - else { - incompletePlaceholders.push(marker); - } - } - return true; - }); - for (const placeholder of incompletePlaceholders) { - if (placeholderDefaultValues.has(placeholder.index)) { - const clone = new Placeholder(placeholder.index); - clone.transform = placeholder.transform; - for (const child of placeholderDefaultValues.get(placeholder.index)) { - let marker = child.clone(); - if (clone.transform) { - if (marker instanceof Text) { - marker = new Text(clone.transform.resolve(marker.value)); - } - else { - for (let child of marker.children) { - if (child instanceof Text) { - marker.replace(child, [new Text(clone.transform.resolve(child.value))]); - break; - } - } - } - } - clone.appendChild(marker); - } - snippet.replace(placeholder, [clone]); - } - } - if (!placeholderDefaultValues.has(0) && insertFinalTabstop) { - // the snippet uses placeholders but has no - // final tabstop defined -> insert at the end - snippet.appendChild(new Placeholder(0)); - } - return snippet; - } - _accept(type, value) { - if (type === undefined || this._token.type === type) { - let ret = !value ? true : this._scanner.tokenText(this._token); - this._token = this._scanner.next(); - return ret; - } - return false; - } - _backTo(token) { - this._scanner.pos = token.pos + token.len; - this._token = token; - return false; - } - _until(type) { - if (this._token.type === 14 /* EOF */) { - return false; - } - let start = this._token; - while (this._token.type !== type) { - this._token = this._scanner.next(); - if (this._token.type === 14 /* EOF */) { - return false; - } - } - let value = this._scanner.value.substring(start.pos, this._token.pos); - this._token = this._scanner.next(); - return value; - } - _parse(marker) { - return this._parseEscaped(marker) - || this._parseTabstopOrVariableName(marker) - || this._parseComplexPlaceholder(marker) - || this._parseComplexVariable(marker) - || this._parseAnything(marker); - } - // \$, \\, \} -> just text - _parseEscaped(marker) { - let value; - // eslint-disable-next-line no-cond-assign - if (value = this._accept(5 /* Backslash */, true)) { - // saw a backslash, append escaped token or that backslash - value = this._accept(0 /* Dollar */, true) - || this._accept(4 /* CurlyClose */, true) - || this._accept(5 /* Backslash */, true) - || value; - marker.appendChild(new Text(value)); - return true; - } - return false; - } - // $foo -> variable, $1 -> tabstop - _parseTabstopOrVariableName(parent) { - let value; - const token = this._token; - const match = this._accept(0 /* Dollar */) - && (value = this._accept(9 /* VariableName */, true) || this._accept(8 /* Int */, true)); - if (!match) { - return this._backTo(token); - } - parent.appendChild(/^\d+$/.test(value) - ? new Placeholder(Number(value)) - : new Variable(value)); - return true; - } - // ${1:}, ${1} -> placeholder - _parseComplexPlaceholder(parent) { - let index; - const token = this._token; - const match = this._accept(0 /* Dollar */) - && this._accept(3 /* CurlyOpen */) - && (index = this._accept(8 /* Int */, true)); - if (!match) { - return this._backTo(token); - } - const placeholder = new Placeholder(Number(index)); - if (this._accept(1 /* Colon */)) { - // ${1:} - // eslint-disable-next-line no-constant-condition - while (true) { - // ...} -> done - if (this._accept(4 /* CurlyClose */)) { - parent.appendChild(placeholder); - return true; - } - if (this._parse(placeholder)) { - continue; - } - // fallback - parent.appendChild(new Text('${' + index + ':')); - placeholder.children.forEach(parent.appendChild, parent); - return true; - } - } - else if (placeholder.index > 0 && this._accept(7 /* Pipe */)) { - // ${1|one,two,three|} - const choice = new Choice(); - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._parseChoiceElement(choice)) { - if (this._accept(2 /* Comma */)) { - // opt, -> more - continue; - } - if (this._accept(7 /* Pipe */)) { - placeholder.appendChild(choice); - if (this._accept(4 /* CurlyClose */)) { - // ..|} -> done - parent.appendChild(placeholder); - return true; - } - } - } - this._backTo(token); - return false; - } - } - else if (this._accept(6 /* Forwardslash */)) { - // ${1///} - if (this._parseTransform(placeholder)) { - parent.appendChild(placeholder); - return true; - } - this._backTo(token); - return false; - } - else if (this._accept(4 /* CurlyClose */)) { - // ${1} - parent.appendChild(placeholder); - return true; - } - else { - // ${1 <- missing curly or colon - return this._backTo(token); - } - } - _parseChoiceElement(parent) { - const token = this._token; - const values = []; - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._token.type === 2 /* Comma */ || this._token.type === 7 /* Pipe */) { - break; - } - let value; - // eslint-disable-next-line no-cond-assign - if (value = this._accept(5 /* Backslash */, true)) { - // \, \|, or \\ - value = this._accept(2 /* Comma */, true) - || this._accept(7 /* Pipe */, true) - || this._accept(5 /* Backslash */, true) - || value; - } - else { - value = this._accept(undefined, true); - } - if (!value) { - // EOF - this._backTo(token); - return false; - } - values.push(value); - } - if (values.length === 0) { - this._backTo(token); - return false; - } - parent.appendChild(new Text(values.join(''))); - return true; - } - // ${foo:}, ${foo} -> variable - _parseComplexVariable(parent) { - let name; - const token = this._token; - const match = this._accept(0 /* Dollar */) - && this._accept(3 /* CurlyOpen */) - && (name = this._accept(9 /* VariableName */, true)); - if (!match) { - return this._backTo(token); - } - const variable = new Variable(name); - if (this._accept(1 /* Colon */)) { - // ${foo:} - // eslint-disable-next-line no-constant-condition - while (true) { - // ...} -> done - if (this._accept(4 /* CurlyClose */)) { - parent.appendChild(variable); - return true; - } - if (this._parse(variable)) { - continue; - } - // fallback - parent.appendChild(new Text('${' + name + ':')); - variable.children.forEach(parent.appendChild, parent); - return true; - } - } - else if (this._accept(6 /* Forwardslash */)) { - // ${foo///} - if (this._parseTransform(variable)) { - parent.appendChild(variable); - return true; - } - this._backTo(token); - return false; - } - else if (this._accept(4 /* CurlyClose */)) { - // ${foo} - parent.appendChild(variable); - return true; - } - else { - // ${foo <- missing curly or colon - return this._backTo(token); - } - } - _parseTransform(parent) { - // ...//} - let transform = new Transform(); - let regexValue = ''; - let regexOptions = ''; - // (1) /regex - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(6 /* Forwardslash */)) { - break; - } - let escaped; - // eslint-disable-next-line no-cond-assign - if (escaped = this._accept(5 /* Backslash */, true)) { - escaped = this._accept(6 /* Forwardslash */, true) || escaped; - regexValue += escaped; - continue; - } - if (this._token.type !== 14 /* EOF */) { - regexValue += this._accept(undefined, true); - continue; - } - return false; - } - // (2) /format - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(6 /* Forwardslash */)) { - break; - } - let escaped; - // eslint-disable-next-line no-cond-assign - if (escaped = this._accept(5 /* Backslash */, true)) { - escaped = this._accept(6 /* Forwardslash */, true) || escaped; - transform.appendChild(new Text(escaped)); - continue; - } - if (this._parseFormatString(transform) || this._parseAnything(transform)) { - let text = transform.children[0]; - if (text && text.value && text.value.includes('\\n')) { - text.value = text.value.replace(/\\n/g, '\n'); - } - continue; - } - return false; - } - // (3) /option - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(4 /* CurlyClose */)) { - break; - } - if (this._token.type !== 14 /* EOF */) { - regexOptions += this._accept(undefined, true); - continue; - } - return false; - } - try { - transform.regexp = new RegExp(regexValue, regexOptions); - } - catch (e) { - // invalid regexp - return false; - } - parent.transform = transform; - return true; - } - _parseFormatString(parent) { - const token = this._token; - if (!this._accept(0 /* Dollar */)) { - return false; - } - let complex = false; - if (this._accept(3 /* CurlyOpen */)) { - complex = true; - } - let index = this._accept(8 /* Int */, true); - if (!index) { - this._backTo(token); - return false; - } - else if (!complex) { - // $1 - parent.appendChild(new FormatString(Number(index))); - return true; - } - else if (this._accept(4 /* CurlyClose */)) { - // ${1} - parent.appendChild(new FormatString(Number(index))); - return true; - } - else if (!this._accept(1 /* Colon */)) { - this._backTo(token); - return false; - } - if (this._accept(6 /* Forwardslash */)) { - // ${1:/upcase} - let shorthand = this._accept(9 /* VariableName */, true); - if (!shorthand || !this._accept(4 /* CurlyClose */)) { - this._backTo(token); - return false; - } - else { - parent.appendChild(new FormatString(Number(index), shorthand)); - return true; - } - } - else if (this._accept(11 /* Plus */)) { - // ${1:+} - let ifValue = this._until(4 /* CurlyClose */); - if (ifValue) { - parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined)); - return true; - } - } - else if (this._accept(12 /* Dash */)) { - // ${2:-} - let elseValue = this._until(4 /* CurlyClose */); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); - return true; - } - } - else if (this._accept(13 /* QuestionMark */)) { - // ${2:?:} - let ifValue = this._until(1 /* Colon */); - if (ifValue) { - let elseValue = this._until(4 /* CurlyClose */); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue)); - return true; - } - } - } - else { - // ${1:} - let elseValue = this._until(4 /* CurlyClose */); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); - return true; - } - } - this._backTo(token); - return false; - } - _parseAnything(marker) { - if (this._token.type !== 14 /* EOF */) { - let text = this._scanner.tokenText(this._token); - marker.appendChild(new Text(text)); - this._accept(undefined); - return true; - } - return false; - } -} -exports.SnippetParser = SnippetParser; -//# sourceMappingURL=parser.js.map - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.normalizeSnippetString = exports.SnippetSession = void 0; -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const completion_1 = tslib_1.__importDefault(__webpack_require__(340)); -const position_1 = __webpack_require__(315); -const string_1 = __webpack_require__(314); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const snippet_1 = __webpack_require__(613); -const variableResolve_1 = __webpack_require__(614); -const logger = __webpack_require__(64)('snippets-session'); -class SnippetSession { - constructor(nvim, bufnr) { - this.nvim = nvim; - this.bufnr = bufnr; - this._isActive = false; - this._currId = 0; - // Get state of line where we inserted - this.applying = false; - this.preferComplete = false; - this._snippet = null; - this._onCancelEvent = new vscode_languageserver_protocol_1.Emitter(); - this.onCancel = this._onCancelEvent.event; - let config = workspace_1.default.getConfiguration('coc.preferences'); - let suggest = workspace_1.default.getConfiguration('suggest'); - this.preferComplete = config.get('preferCompleteThanJumpPlaceholder', suggest.get('preferCompleteThanJumpPlaceholder', false)); - } - async start(snippetString, select = true, range) { - const { document } = this; - if (!document || !document.attached) - return false; - if (!range) { - let position = await workspace_1.default.getCursorPosition(); - range = vscode_languageserver_protocol_1.Range.create(position, position); - } - let position = range.start; - const formatOptions = await workspace_1.default.getFormatOptions(this.document.uri); - const currentLine = document.getline(position.line); - const currentIndent = currentLine.match(/^\s*/)[0]; - let inserted = normalizeSnippetString(snippetString, currentIndent, formatOptions); - const resolver = new variableResolve_1.SnippetVariableResolver(); - await resolver.init(document); - const snippet = new snippet_1.CocSnippet(inserted, position, resolver); - const edit = vscode_languageserver_protocol_1.TextEdit.replace(range, snippet.toString()); - if (snippetString.endsWith('\n') - && currentLine.slice(position.character).length) { - // make next line same indent - edit.newText = edit.newText + currentIndent; - inserted = inserted + currentIndent; - } - await document.patchChange(); - this.applying = true; - await document.applyEdits([edit]); - this.applying = false; - if (this._isActive) { - // find valid placeholder - let placeholder = this.findPlaceholder(range); - // insert to placeholder - if (placeholder && !placeholder.isFinalTabstop) { - // don't repeat snippet insert - let index = this.snippet.insertSnippet(placeholder, inserted, range); - let p = this.snippet.getPlaceholder(index); - this._currId = p.id; - if (select) - await this.selectPlaceholder(p); - return true; - } - } - if (snippet.isPlainText) { - this.deactivate(); - let placeholder = snippet.finalPlaceholder; - await workspace_1.default.moveTo(placeholder.range.start); - return false; - } - // new snippet - this._snippet = snippet; - this._currId = snippet.firstPlaceholder.id; - if (select) - await this.selectPlaceholder(snippet.firstPlaceholder); - this.activate(); - return true; - } - activate() { - if (this._isActive) - return; - this._isActive = true; - this.nvim.call('coc#snippet#enable', [], true); - } - deactivate() { - if (this._isActive) { - this._isActive = false; - this._snippet = null; - this.nvim.call('coc#snippet#disable', [], true); - logger.debug("[SnippetManager::cancel]"); - } - this._onCancelEvent.fire(void 0); - this._onCancelEvent.dispose(); - } - get isActive() { - return this._isActive; - } - async nextPlaceholder() { - if (!this.isActive) - return; - await this.document.patchChange(); - let curr = this.placeholder; - let next = this.snippet.getNextPlaceholder(curr.index); - await this.selectPlaceholder(next); - } - async previousPlaceholder() { - if (!this.isActive) - return; - await this.document.patchChange(); - let curr = this.placeholder; - let prev = this.snippet.getPrevPlaceholder(curr.index); - await this.selectPlaceholder(prev); - } - async synchronizeUpdatedPlaceholders(change) { - if (!this.isActive || !this.document || this.applying) - return; - let edit = { range: change.range, newText: change.text }; - let { snippet } = this; - // change outside range - let adjusted = snippet.adjustTextEdit(edit); - if (adjusted) - return; - if (position_1.comparePosition(edit.range.start, snippet.range.end) > 0) { - if (!edit.newText) - return; - logger.info('Content change after snippet, cancelling snippet session'); - this.deactivate(); - return; - } - let placeholder = this.findPlaceholder(edit.range); - if (!placeholder) { - logger.info('Change outside placeholder, cancelling snippet session'); - this.deactivate(); - return; - } - if (placeholder.isFinalTabstop && snippet.finalCount <= 1) { - logger.info('Change final placeholder, cancelling snippet session'); - this.deactivate(); - return; - } - this._currId = placeholder.id; - let { edits, delta } = snippet.updatePlaceholder(placeholder, edit); - if (!edits.length) - return; - this.applying = true; - await this.document.applyEdits(edits); - this.applying = false; - if (delta) { - await this.nvim.call('coc#util#move_cursor', delta); - } - } - async selectCurrentPlaceholder(triggerAutocmd = true) { - let placeholder = this.snippet.getPlaceholderById(this._currId); - if (placeholder) - await this.selectPlaceholder(placeholder, triggerAutocmd); - } - async selectPlaceholder(placeholder, triggerAutocmd = true) { - let { nvim, document } = this; - if (!document || !placeholder) - return; - let { start, end } = placeholder.range; - const len = end.character - start.character; - const col = string_1.byteLength(document.getline(start.line).slice(0, start.character)) + 1; - this._currId = placeholder.id; - if (placeholder.choice) { - await nvim.call('coc#snippet#show_choices', [start.line + 1, col, len, placeholder.choice]); - if (triggerAutocmd) - nvim.call('coc#util#do_autocmd', ['CocJumpPlaceholder'], true); - } - else { - await this.select(placeholder, triggerAutocmd); - } - } - async select(placeholder, triggerAutocmd = true) { - let { range, value, isFinalTabstop } = placeholder; - let { document, nvim } = this; - let { start, end } = range; - let { textDocument } = document; - let len = textDocument.offsetAt(end) - textDocument.offsetAt(start); - let line = document.getline(start.line); - let col = line ? string_1.byteLength(line.slice(0, start.character)) : 0; - let endLine = document.getline(end.line); - let endCol = endLine ? string_1.byteLength(endLine.slice(0, end.character)) : 0; - nvim.setVar('coc_last_placeholder', { - current_text: value, - start: { line: start.line, col }, - end: { line: end.line, col: endCol } - }, true); - let [ve, selection, pumvisible, mode] = await nvim.eval('[&virtualedit, &selection, pumvisible(), mode()]'); - let move_cmd = ''; - if (pumvisible && this.preferComplete) { - let pre = completion_1.default.hasSelected() ? '' : '\\'; - await nvim.eval(`feedkeys("${pre}\\", 'in')`); - return; - } - // create move cmd - if (mode != 'n') - move_cmd += "\\"; - if (len == 0) { - if (col == 0 || (!mode.startsWith('i') && col < string_1.byteLength(line))) { - move_cmd += 'i'; - } - else { - move_cmd += 'a'; - } - } - else { - move_cmd += 'v'; - endCol = await this.getVirtualCol(end.line + 1, endCol); - if (selection == 'inclusive') { - if (end.character == 0) { - move_cmd += `${end.line}G`; - } - else { - move_cmd += `${end.line + 1}G${endCol}|`; - } - } - else if (selection == 'old') { - move_cmd += `${end.line + 1}G${endCol}|`; - } - else { - move_cmd += `${end.line + 1}G${endCol + 1}|`; - } - col = await this.getVirtualCol(start.line + 1, col); - move_cmd += `o${start.line + 1}G${col + 1}|o\\`; - } - if (mode == 'i' && move_cmd == "\\a") { - move_cmd = ''; - } - nvim.pauseNotification(); - nvim.setOption('virtualedit', 'onemore', true); - nvim.call('cursor', [start.line + 1, col + (move_cmd == 'a' ? 0 : 1)], true); - if (move_cmd) { - nvim.call('eval', [`feedkeys("${move_cmd}", 'in')`], true); - } - if (mode == 'i') { - nvim.call('coc#_cancel', [], true); - } - nvim.setOption('virtualedit', ve, true); - if (isFinalTabstop) { - if (this.snippet.finalCount == 1) { - logger.info('Jump to final placeholder, cancelling snippet session'); - this.deactivate(); - } - else { - nvim.call('coc#snippet#disable', [], true); - } - } - if (workspace_1.default.env.isVim) - nvim.command('redraw', true); - await nvim.resumeNotification(); - if (triggerAutocmd) - nvim.call('coc#util#do_autocmd', ['CocJumpPlaceholder'], true); - } - async getVirtualCol(line, col) { - let { nvim } = this; - return await nvim.eval(`virtcol([${line}, ${col}])`); - } - async checkPosition() { - if (!this.isActive) - return; - let position = await workspace_1.default.getCursorPosition(); - if (this.snippet && position_1.positionInRange(position, this.snippet.range) != 0) { - logger.info('Cursor insert out of range, cancelling snippet session'); - this.deactivate(); - } - } - findPlaceholder(range) { - if (!this.snippet) - return null; - let { placeholder } = this; - if (placeholder && position_1.rangeInRange(range, placeholder.range)) - return placeholder; - return this.snippet.getPlaceholderByRange(range) || null; - } - get placeholder() { - if (!this.snippet) - return null; - return this.snippet.getPlaceholderById(this._currId); - } - get snippet() { - return this._snippet; - } - get document() { - return workspace_1.default.getDocument(this.bufnr); - } -} -exports.SnippetSession = SnippetSession; -function normalizeSnippetString(snippet, indent, opts) { - let lines = snippet.split(/\r?\n/); - let ind = opts.insertSpaces ? ' '.repeat(opts.tabSize) : '\t'; - let tabSize = opts.tabSize || 2; - lines = lines.map((line, idx) => { - let space = line.match(/^\s*/)[0]; - let pre = space; - let isTab = space.startsWith('\t'); - if (isTab && opts.insertSpaces) { - pre = ind.repeat(space.length); - } - else if (!isTab && !opts.insertSpaces) { - pre = ind.repeat(space.length / tabSize); - } - return (idx == 0 || line.length == 0 ? '' : indent) + pre + line.slice(space.length); - }); - return lines.join('\n'); -} -exports.normalizeSnippetString = normalizeSnippetString; -//# sourceMappingURL=session.js.map - -/***/ }), -/* 340 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Completion = void 0; -const tslib_1 = __webpack_require__(65); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const sources_1 = tslib_1.__importDefault(__webpack_require__(341)); -const util_1 = __webpack_require__(238); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const complete_1 = tslib_1.__importDefault(__webpack_require__(609)); -const floating_1 = tslib_1.__importDefault(__webpack_require__(611)); -const throttle_1 = tslib_1.__importDefault(__webpack_require__(612)); -const object_1 = __webpack_require__(249); -const string_1 = __webpack_require__(314); -const logger = __webpack_require__(64)('completion'); -const completeItemKeys = ['abbr', 'menu', 'info', 'kind', 'icase', 'dup', 'empty', 'user_data']; -class Completion { - constructor() { - // current input string - this.activated = false; - this.disposables = []; - this.complete = null; - this.recentScores = {}; - this.changedTick = 0; - this.insertCharTs = 0; - this.insertLeaveTs = 0; - } - init() { - this.config = this.getCompleteConfig(); - this.floating = new floating_1.default(); - events_1.default.on('InsertCharPre', this.onInsertCharPre, this, this.disposables); - events_1.default.on('InsertLeave', this.onInsertLeave, this, this.disposables); - events_1.default.on('InsertEnter', this.onInsertEnter, this, this.disposables); - events_1.default.on('TextChangedP', this.onTextChangedP, this, this.disposables); - events_1.default.on('TextChangedI', this.onTextChangedI, this, this.disposables); - let fn = throttle_1.default(this.onPumChange.bind(this), workspace_1.default.isVim ? 200 : 100); - events_1.default.on('CompleteDone', async (item) => { - this.currItem = null; - this.cancelResolve(); - this.floating.close(); - await this.onCompleteDone(item); - }, this, this.disposables); - events_1.default.on('MenuPopupChanged', ev => { - if (!this.activated || this.isCommandLine) - return; - let { completed_item } = ev; - let item = completed_item.hasOwnProperty('word') ? completed_item : null; - if (object_1.equals(item, this.currItem)) - return; - this.cancelResolve(); - this.currItem = item; - fn(ev); - }, this, this.disposables); - workspace_1.default.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('suggest')) { - this.config = this.getCompleteConfig(); - } - }, null, this.disposables); - } - get nvim() { - return workspace_1.default.nvim; - } - get option() { - if (!this.complete) - return null; - return this.complete.option; - } - get isCommandLine() { - var _a; - return (_a = this.document) === null || _a === void 0 ? void 0 : _a.uri.endsWith('%5BCommand%20Line%5D'); - } - addRecent(word, bufnr) { - if (!word) - return; - this.recentScores[`${bufnr}|${word}`] = Date.now(); - } - get isActivated() { - return this.activated; - } - get document() { - if (!this.option) - return null; - return workspace_1.default.getDocument(this.option.bufnr); - } - getCompleteConfig() { - let suggest = workspace_1.default.getConfiguration('suggest'); - function getConfig(key, defaultValue) { - return suggest.get(key, suggest.get(key, defaultValue)); - } - let keepCompleteopt = getConfig('keepCompleteopt', false); - let autoTrigger = getConfig('autoTrigger', 'always'); - if (keepCompleteopt && autoTrigger != 'none') { - let { completeOpt } = workspace_1.default; - if (!completeOpt.includes('noinsert') && !completeOpt.includes('noselect')) { - autoTrigger = 'none'; - } - } - let acceptSuggestionOnCommitCharacter = workspace_1.default.env.pumevent && getConfig('acceptSuggestionOnCommitCharacter', false); - return { - autoTrigger, - keepCompleteopt, - defaultSortMethod: getConfig('defaultSortMethod', 'length'), - removeDuplicateItems: getConfig('removeDuplicateItems', false), - disableMenuShortcut: getConfig('disableMenuShortcut', false), - acceptSuggestionOnCommitCharacter, - disableKind: getConfig('disableKind', false), - disableMenu: getConfig('disableMenu', false), - previewIsKeyword: getConfig('previewIsKeyword', '@,48-57,_192-255'), - enablePreview: getConfig('enablePreview', false), - enablePreselect: getConfig('enablePreselect', false), - maxPreviewWidth: getConfig('maxPreviewWidth', 80), - triggerCompletionWait: getConfig('triggerCompletionWait', 50), - labelMaxLength: getConfig('labelMaxLength', 200), - triggerAfterInsertEnter: getConfig('triggerAfterInsertEnter', false), - noselect: getConfig('noselect', true), - numberSelect: getConfig('numberSelect', false), - maxItemCount: getConfig('maxCompleteItemCount', 50), - timeout: getConfig('timeout', 500), - minTriggerInputLength: getConfig('minTriggerInputLength', 1), - snippetIndicator: getConfig('snippetIndicator', '~'), - fixInsertedWord: getConfig('fixInsertedWord', true), - localityBonus: getConfig('localityBonus', true), - highPrioritySourceLimit: getConfig('highPrioritySourceLimit', null), - lowPrioritySourceLimit: getConfig('lowPrioritySourceLimit', null), - asciiCharactersOnly: getConfig('asciiCharactersOnly', false) - }; - } - async startCompletion(option) { - this.pretext = string_1.byteSlice(option.line, 0, option.colnr - 1); - try { - await this._doComplete(option); - } - catch (e) { - this.stop(); - workspace_1.default.showMessage(`Complete error: ${e.message}`, 'error'); - logger.error(e.stack); - } - } - async resumeCompletion(force = false) { - let { document, complete } = this; - if (!document - || complete.isCanceled - || !complete.results - || complete.results.length == 0) - return; - let search = this.getResumeInput(); - if (search == this.input && !force) - return; - if (!search || search.endsWith(' ') || !search.startsWith(complete.input)) { - this.stop(); - return; - } - this.input = search; - let items = []; - if (complete.isIncomplete) { - await document.patchChange(); - let { changedtick } = document; - items = await complete.completeInComplete(search); - if (complete.isCanceled || document.changedtick != changedtick) - return; - } - else { - items = complete.filterResults(search); - } - if (!complete.isCompleting && items.length === 0) { - this.stop(); - return; - } - await this.showCompletion(complete.option.col, items); - } - hasSelected() { - if (workspace_1.default.env.pumevent) - return this.currItem != null; - if (!this.config.noselect) - return true; - return false; - } - async showCompletion(col, items) { - let { nvim, document, option } = this; - let { numberSelect, disableKind, labelMaxLength, disableMenuShortcut, disableMenu } = this.config; - let preselect = this.config.enablePreselect ? items.findIndex(o => o.preselect) : -1; - if (numberSelect && option.input.length && !/^\d/.test(option.input)) { - items = items.map((item, i) => { - let idx = i + 1; - if (i < 9) { - return Object.assign({}, item, { - abbr: item.abbr ? `${idx} ${item.abbr}` : `${idx} ${item.word}` - }); - } - return item; - }); - nvim.call('coc#_map', [], true); - } - this.changedTick = document.changedtick; - let validKeys = completeItemKeys.slice(); - if (disableKind) - validKeys = validKeys.filter(s => s != 'kind'); - if (disableMenu) - validKeys = validKeys.filter(s => s != 'menu'); - let vimItems = items.map(item => { - let obj = { word: item.word, equal: 1 }; - for (let key of validKeys) { - if (item.hasOwnProperty(key)) { - if (disableMenuShortcut && key == 'menu') { - obj[key] = item[key].replace(/\[.+\]$/, ''); - } - else if (key == 'abbr' && item[key].length > labelMaxLength) { - obj[key] = item[key].slice(0, labelMaxLength); - } - else { - obj[key] = item[key]; - } - } - } - return obj; - }); - nvim.call('coc#_do_complete', [col, vimItems, preselect], true); - } - async _doComplete(option) { - let { source } = option; - let { nvim, config } = this; - let doc = workspace_1.default.getDocument(option.bufnr); - if (!doc || !doc.attached) - return; - // use fixed filetype - option.filetype = doc.filetype; - // current input - this.input = option.input; - let arr = []; - if (source == null) { - arr = sources_1.default.getCompleteSources(option); - } - else { - let s = sources_1.default.getSource(source); - if (s) - arr.push(s); - } - if (!arr.length) - return; - if (option.triggerCharacter) { - await util_1.wait(this.config.triggerCompletionWait); - } - await doc.patchChange(); - // document get changed, not complete - if (doc.changedtick != option.changedtick) - return; - let complete = new complete_1.default(option, doc, this.recentScores, config, arr, nvim); - this.start(complete); - let items = await this.complete.doComplete(); - if (complete.isCanceled) - return; - if (items.length == 0 && !complete.isCompleting) { - this.stop(); - return; - } - complete.onDidComplete(async () => { - let search = this.getResumeInput(); - if (complete.isCanceled || search == null) - return; - if (this.currItem != null && this.completeOpt.includes('noselect')) - return; - let { input } = this.option; - if (search == input) { - let items = complete.filterResults(search, Math.floor(Date.now() / 1000)); - await this.showCompletion(option.col, items); - } - else { - await this.resumeCompletion(); - } - }); - if (items.length) { - let search = this.getResumeInput(); - if (search == option.input) { - await this.showCompletion(option.col, items); - } - else { - await this.resumeCompletion(true); - } - } - } - async onTextChangedP(bufnr, info) { - let { option, document } = this; - let pretext = this.pretext = info.pre; - // avoid trigger filter on pumvisible - if (!option || option.bufnr != bufnr || info.changedtick == this.changedTick) - return; - let hasInsert = this.latestInsert != null; - this.lastInsert = null; - if (info.pre.match(/^\s*/)[0] !== option.line.match(/^\s*/)[0]) { - // Can't handle indent change - this.stop(); - return; - } - // not handle when not triggered by character insert - if (!hasInsert || !pretext) - return; - if (sources_1.default.shouldTrigger(pretext, document.filetype)) { - await this.triggerCompletion(document, pretext, false); - } - else { - await this.resumeCompletion(); - } - } - async onTextChangedI(bufnr, info) { - let { nvim, latestInsertChar, option } = this; - let noChange = this.pretext == info.pre; - let pretext = this.pretext = info.pre; - this.lastInsert = null; - let document = workspace_1.default.getDocument(bufnr); - if (!document || !document.attached) - return; - // try trigger on character type - if (!this.activated) { - if (!latestInsertChar) - return; - await this.triggerCompletion(document, this.pretext); - return; - } - // Ignore change with other buffer - if (!option) - return; - if (bufnr != option.bufnr - || option.linenr != info.lnum - || option.col >= info.col - 1) { - this.stop(); - return; - } - // Completion is canceled by - if (noChange && !latestInsertChar) { - this.stop(); - return; - } - // Check commit character - if (pretext - && this.currItem - && this.config.acceptSuggestionOnCommitCharacter - && latestInsertChar) { - let resolvedItem = this.getCompleteItem(this.currItem); - let last = pretext[pretext.length - 1]; - if (sources_1.default.shouldCommit(resolvedItem, last)) { - let { linenr, col, line, colnr } = this.option; - this.stop(); - let { word } = resolvedItem; - let newLine = `${line.slice(0, col)}${word}${latestInsertChar}${line.slice(colnr - 1)}`; - await nvim.call('coc#util#setline', [linenr, newLine]); - let curcol = col + word.length + 2; - await nvim.call('cursor', [linenr, curcol]); - await document.patchChange(); - return; - } - } - // prefer trigger completion - if (sources_1.default.shouldTrigger(pretext, document.filetype)) { - await this.triggerCompletion(document, pretext, false); - } - else { - await this.resumeCompletion(); - } - } - async triggerCompletion(document, pre, checkTrigger = true) { - if (this.config.autoTrigger == 'none') - return; - // check trigger - if (checkTrigger) { - let shouldTrigger = this.shouldTrigger(document, pre); - if (!shouldTrigger) - return; - } - await document.patchChange(); - let option = await this.nvim.call('coc#util#get_complete_option'); - if (!option) - return; - if (pre.length) { - option.triggerCharacter = pre.slice(-1); - } - logger.debug('trigger completion with', option); - await this.startCompletion(option); - } - async onCompleteDone(item) { - let { document, isActivated } = this; - if (!isActivated || !document || !item.hasOwnProperty('word')) - return; - let opt = Object.assign({}, this.option); - let resolvedItem = this.getCompleteItem(item); - this.stop(); - if (!resolvedItem) - return; - let timestamp = this.insertCharTs; - let insertLeaveTs = this.insertLeaveTs; - try { - await sources_1.default.doCompleteResolve(resolvedItem, (new vscode_languageserver_protocol_1.CancellationTokenSource()).token); - this.addRecent(resolvedItem.word, document.bufnr); - // Wait possible TextChangedI - await util_1.wait(50); - if (this.insertCharTs != timestamp - || this.insertLeaveTs != insertLeaveTs) - return; - let [visible, lnum, pre] = await this.nvim.eval(`[pumvisible(),line('.'),strpart(getline('.'), 0, col('.') - 1)]`); - if (visible || lnum != opt.linenr || this.activated || !pre.endsWith(resolvedItem.word)) - return; - await document.patchChange(); - await sources_1.default.doCompleteDone(resolvedItem, opt); - } - catch (e) { - logger.error(`error on complete done`, e.stack); - } - } - async onInsertLeave() { - this.insertLeaveTs = Date.now(); - this.stop(); - } - async onInsertEnter(bufnr) { - if (!this.config.triggerAfterInsertEnter || this.config.autoTrigger !== 'always') - return; - let doc = workspace_1.default.getDocument(bufnr); - if (!doc || !doc.attached) - return; - let pre = await this.nvim.eval(`strpart(getline('.'), 0, col('.') - 1)`); - if (!pre) - return; - await this.triggerCompletion(doc, pre); - } - async onInsertCharPre(character) { - this.lastInsert = { - character, - timestamp: Date.now(), - }; - this.insertCharTs = this.lastInsert.timestamp; - } - get latestInsert() { - let { lastInsert } = this; - if (!lastInsert || Date.now() - lastInsert.timestamp > 500) { - return null; - } - return lastInsert; - } - get latestInsertChar() { - let { latestInsert } = this; - if (!latestInsert) - return ''; - return latestInsert.character; - } - shouldTrigger(document, pre) { - if (pre.length == 0 || /\s/.test(pre[pre.length - 1])) - return false; - let autoTrigger = this.config.autoTrigger; - if (autoTrigger == 'none') - return false; - if (sources_1.default.shouldTrigger(pre, document.filetype)) - return true; - if (autoTrigger !== 'always' || this.isActivated) - return false; - let last = pre.slice(-1); - if (last && (document.isWord(pre.slice(-1)) || last.codePointAt(0) > 255)) { - let minLength = this.config.minTriggerInputLength; - if (minLength == 1) - return true; - let input = this.getInput(document, pre); - return input.length >= minLength; - } - return false; - } - async onPumChange(ev) { - if (!this.activated) - return; - let { completed_item, col, row, height, width, scrollbar } = ev; - let bounding = { col, row, height, width, scrollbar }; - let resolvedItem = this.getCompleteItem(completed_item); - if (!resolvedItem) { - this.floating.close(); - return; - } - let source = this.resolveTokenSource = new vscode_languageserver_protocol_1.CancellationTokenSource(); - let { token } = source; - await sources_1.default.doCompleteResolve(resolvedItem, token); - this.resolveTokenSource = null; - if (token.isCancellationRequested) - return; - let docs = resolvedItem.documentation; - if (!docs && resolvedItem.info) { - let { info } = resolvedItem; - let isText = /^[\w-\s.,\t]+$/.test(info); - docs = [{ filetype: isText ? 'txt' : this.document.filetype, content: info }]; - } - if (!this.isActivated) - return; - if (!docs || docs.length == 0) { - this.floating.close(); - } - else { - await this.floating.show(docs, bounding, token); - if (!this.isActivated) { - this.floating.close(); - } - } - } - start(complete) { - let { activated } = this; - this.activated = true; - if (activated) { - this.complete.dispose(); - } - this.complete = complete; - if (!this.config.keepCompleteopt) { - this.nvim.command(`noa set completeopt=${this.completeOpt}`, true); - } - } - cancelResolve() { - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel(); - this.resolveTokenSource = null; - } - } - stop() { - let { nvim } = this; - if (!this.activated) - return; - this.currItem = null; - this.activated = false; - if (this.complete) { - this.complete.dispose(); - this.complete = null; - } - nvim.pauseNotification(); - this.floating.close(); - if (this.config.numberSelect) { - nvim.call('coc#_unmap', [], true); - } - if (!this.config.keepCompleteopt) { - this.nvim.command(`noa set completeopt=${workspace_1.default.completeOpt}`, true); - } - nvim.command(`let g:coc#_context['candidates'] = []`, true); - nvim.call('coc#_hide', [], true); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true); - } - getInput(document, pre) { - let input = ''; - for (let i = pre.length - 1; i >= 0; i--) { - let ch = i == 0 ? null : pre[i - 1]; - if (!ch || !document.isWord(ch)) { - input = pre.slice(i, pre.length); - break; - } - } - return input; - } - getResumeInput() { - let { option, pretext } = this; - if (!option) - return null; - let buf = Buffer.from(pretext, 'utf8'); - if (buf.length < option.col) - return null; - let input = buf.slice(option.col).toString('utf8'); - if (option.blacklist && option.blacklist.includes(input)) - return null; - return input; - } - get completeOpt() { - let { noselect, enablePreview } = this.config; - let preview = enablePreview && !workspace_1.default.env.pumevent ? ',preview' : ''; - if (noselect) - return `noselect,menuone${preview}`; - return `noinsert,menuone${preview}`; - } - getCompleteItem(item) { - if (!this.complete || item == null) - return null; - return this.complete.resolveCompletionItem(item); - } - dispose() { - util_1.disposeAll(this.disposables); - } -} -exports.Completion = Completion; -exports.default = new Completion(); -//# sourceMappingURL=index.js.map - -/***/ }), -/* 341 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Sources = void 0; -const tslib_1 = __webpack_require__(65); -const fast_diff_1 = tslib_1.__importDefault(__webpack_require__(271)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const util_1 = tslib_1.__importDefault(__webpack_require__(74)); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const extensions_1 = tslib_1.__importDefault(__webpack_require__(342)); -const source_1 = tslib_1.__importDefault(__webpack_require__(604)); -const source_vim_1 = tslib_1.__importDefault(__webpack_require__(605)); -const types_1 = __webpack_require__(297); -const util_2 = __webpack_require__(238); -const fs_2 = __webpack_require__(306); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const string_1 = __webpack_require__(314); -const logger = __webpack_require__(64)('sources'); -class Sources { - constructor() { - this.sourceMap = new Map(); - this.disposables = []; - this.remoteSourcePaths = []; - } - get nvim() { - return workspace_1.default.nvim; - } - createNativeSources() { - try { - this.disposables.push((__webpack_require__(606)).regist(this.sourceMap)); - this.disposables.push((__webpack_require__(607)).regist(this.sourceMap)); - this.disposables.push((__webpack_require__(608)).regist(this.sourceMap)); - } - catch (e) { - console.error('Create source error:' + e.message); - } - } - async createVimSourceExtension(nvim, filepath) { - let name = path_1.default.basename(filepath, '.vim'); - try { - await nvim.command(`source ${filepath}`); - let fns = await nvim.call('coc#util#remote_fns', name); - for (let fn of ['init', 'complete']) { - if (!fns.includes(fn)) { - workspace_1.default.showMessage(`${fn} not found for source ${name}`, 'error'); - return null; - } - } - let props = await nvim.call(`coc#source#${name}#init`, []); - let packageJSON = { - name: `coc-source-${name}`, - engines: { - coc: ">= 0.0.1" - }, - activationEvents: props.filetypes ? props.filetypes.map(f => `onLanguage:${f}`) : ['*'], - contributes: { - configuration: { - properties: { - [`coc.source.${name}.enable`]: { - type: 'boolean', - default: true - }, - [`coc.source.${name}.firstMatch`]: { - type: 'boolean', - default: !!props.firstMatch - }, - [`coc.source.${name}.triggerCharacters`]: { - type: 'number', - default: props.triggerCharacters || [] - }, - [`coc.source.${name}.priority`]: { - type: 'number', - default: props.priority || 9 - }, - [`coc.source.${name}.shortcut`]: { - type: 'string', - default: props.shortcut || name.slice(0, 3).toUpperCase(), - description: 'Shortcut text shown in complete menu.' - }, - [`coc.source.${name}.disableSyntaxes`]: { - type: 'array', - default: [], - items: { - type: 'string' - } - }, - [`coc.source.${name}.filetypes`]: { - type: 'array', - default: props.filetypes || null, - description: 'Enabled filetypes.', - items: { - type: 'string' - } - } - } - } - } - }; - let source = new source_vim_1.default({ - name, - filepath, - sourceType: types_1.SourceType.Remote, - optionalFns: fns.filter(n => !['init', 'complete'].includes(n)) - }); - let isActive = false; - let extension = { - id: packageJSON.name, - packageJSON, - exports: void 0, - extensionPath: filepath, - activate: () => { - isActive = true; - this.addSource(source); - return Promise.resolve(); - } - }; - Object.defineProperty(extension, 'isActive', { - get: () => isActive - }); - extensions_1.default.registerExtension(extension, () => { - isActive = false; - this.removeSource(source); - }); - } - catch (e) { - workspace_1.default.showMessage(`Error on create vim source ${name}: ${e.message}`, 'error'); - } - } - createRemoteSources() { - let { runtimepath } = workspace_1.default.env; - let paths = runtimepath.split(','); - for (let path of paths) { - this.createVimSources(path).logError(); - } - } - async createVimSources(pluginPath) { - if (this.remoteSourcePaths.includes(pluginPath)) - return; - this.remoteSourcePaths.push(pluginPath); - let folder = path_1.default.join(pluginPath, 'autoload/coc/source'); - let stat = await fs_2.statAsync(folder); - if (stat && stat.isDirectory()) { - let arr = await util_1.default.promisify(fs_1.default.readdir)(folder); - arr = arr.filter(s => s.endsWith('.vim')); - let files = arr.map(s => path_1.default.join(folder, s)); - if (files.length == 0) - return; - await Promise.all(files.map(p => this.createVimSourceExtension(this.nvim, p))); - } - } - init() { - this.createNativeSources(); - this.createRemoteSources(); - events_1.default.on('BufEnter', this.onDocumentEnter, this, this.disposables); - workspace_1.default.watchOption('runtimepath', async (oldValue, newValue) => { - let result = fast_diff_1.default(oldValue, newValue); - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, '').split(','); - for (let p of paths) { - if (p) - await this.createVimSources(p); - } - } - } - }, this.disposables); - } - get names() { - return Array.from(this.sourceMap.keys()); - } - get sources() { - return Array.from(this.sourceMap.values()); - } - has(name) { - return this.names.findIndex(o => o == name) != -1; - } - getSource(name) { - if (!name) - return null; - return this.sourceMap.get(name) || null; - } - async doCompleteResolve(item, token) { - let source = this.getSource(item.source); - if (source && typeof source.onCompleteResolve == 'function') { - try { - await Promise.resolve(source.onCompleteResolve(item, token)); - } - catch (e) { - logger.error('Error on complete resolve:', e.stack); - } - } - } - async doCompleteDone(item, opt) { - let data = JSON.parse(item.user_data); - let source = this.getSource(data.source); - if (source && typeof source.onCompleteDone === 'function') { - await Promise.resolve(source.onCompleteDone(item, opt)); - } - } - shouldCommit(item, commitCharacter) { - if (!item || !item.source) - return false; - let source = this.getSource(item.source); - if (source && source.sourceType == types_1.SourceType.Service && typeof source.shouldCommit === 'function') { - return source.shouldCommit(item, commitCharacter); - } - return false; - } - getCompleteSources(opt) { - let { filetype } = opt; - let pre = string_1.byteSlice(opt.line, 0, opt.colnr - 1); - let isTriggered = opt.input == '' && !!opt.triggerCharacter; - if (isTriggered) - return this.getTriggerSources(pre, filetype); - return this.getNormalSources(opt.filetype); - } - /** - * Get sources should be used without trigger. - * - * @param {string} filetype - * @returns {ISource[]} - */ - getNormalSources(filetype) { - return this.sources.filter(source => { - let { filetypes, triggerOnly, enable } = source; - if (!enable || triggerOnly || (filetypes && !filetypes.includes(filetype))) { - return false; - } - if (this.disabledByLanguageId(source, filetype)) { - return false; - } - return true; - }); - } - checkTrigger(source, pre, character) { - let { triggerCharacters, triggerPatterns } = source; - if (!triggerCharacters && !triggerPatterns) - return false; - if (character && triggerCharacters && triggerCharacters.includes(character)) { - return true; - } - if (triggerPatterns && triggerPatterns.findIndex(p => p.test(pre)) !== -1) { - return true; - } - return false; - } - shouldTrigger(pre, languageId) { - let sources = this.getTriggerSources(pre, languageId); - return sources.length > 0; - } - getTriggerSources(pre, languageId) { - let character = pre.length ? pre[pre.length - 1] : ''; - if (!character) - return []; - return this.sources.filter(source => { - let { filetypes, enable } = source; - if (!enable || (filetypes && !filetypes.includes(languageId))) { - return false; - } - if (this.disabledByLanguageId(source, languageId)) - return false; - return this.checkTrigger(source, pre, character); - }); - } - addSource(source) { - let { name } = source; - if (this.names.includes(name)) { - workspace_1.default.showMessage(`Source "${name}" recreated`, 'warning'); - } - this.sourceMap.set(name, source); - return vscode_languageserver_protocol_1.Disposable.create(() => { - this.sourceMap.delete(name); - }); - } - removeSource(source) { - let name = typeof source == 'string' ? source : source.name; - if (source == this.sourceMap.get(name)) { - this.sourceMap.delete(name); - } - } - async refresh(name) { - for (let source of this.sources) { - if (!name || source.name == name) { - if (typeof source.refresh === 'function') { - await Promise.resolve(source.refresh()); - } - } - } - } - toggleSource(name) { - if (!name) - return; - let source = this.getSource(name); - if (!source) - return; - if (typeof source.toggle === 'function') { - source.toggle(); - } - } - sourceStats() { - let res = []; - let items = this.sources; - for (let item of items) { - res.push({ - name: item.name, - priority: item.priority, - triggerCharacters: item.triggerCharacters || [], - shortcut: item.shortcut || '', - filetypes: item.filetypes || [], - filepath: item.filepath || '', - type: item.sourceType == types_1.SourceType.Native - ? 'native' : item.sourceType == types_1.SourceType.Remote - ? 'remote' : 'service', - disabled: !item.enable - }); - } - return res; - } - onDocumentEnter(bufnr) { - let { sources } = this; - for (let s of sources) { - if (!s.enable) - continue; - if (typeof s.onEnter == 'function') { - s.onEnter(bufnr); - } - } - } - createSource(config) { - if (!config.name || !config.doComplete) { - console.error(`name and doComplete required for createSource`); - return; - } - let source = new source_1.default(Object.assign({ sourceType: types_1.SourceType.Service }, config)); - return this.addSource(source); - } - disabledByLanguageId(source, languageId) { - let map = workspace_1.default.env.disabledSources; - let list = map ? map[languageId] : []; - return Array.isArray(list) && list.includes(source.name); - } - dispose() { - util_2.disposeAll(this.disposables); - } -} -exports.Sources = Sources; -exports.default = new Sources(); -//# sourceMappingURL=sources.js.map - -/***/ }), -/* 342 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Extensions = void 0; -const tslib_1 = __webpack_require__(65); -const debounce_1 = __webpack_require__(240); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const isuri_1 = tslib_1.__importDefault(__webpack_require__(241)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const rimraf_1 = tslib_1.__importDefault(__webpack_require__(279)); -const semver_1 = tslib_1.__importDefault(__webpack_require__(1)); -const util_1 = __webpack_require__(74); -const vscode_languageserver_protocol_1 = __webpack_require__(211); -const vscode_uri_1 = __webpack_require__(243); -const which_1 = tslib_1.__importDefault(__webpack_require__(244)); -const commands_1 = tslib_1.__importDefault(__webpack_require__(252)); -const events_1 = tslib_1.__importDefault(__webpack_require__(210)); -const db_1 = tslib_1.__importDefault(__webpack_require__(311)); -const floatFactory_1 = tslib_1.__importDefault(__webpack_require__(254)); -const installBuffer_1 = tslib_1.__importDefault(__webpack_require__(343)); -const installer_1 = __webpack_require__(344); -const memos_1 = tslib_1.__importDefault(__webpack_require__(499)); -const types_1 = __webpack_require__(297); -const util_2 = __webpack_require__(238); -const array_1 = __webpack_require__(257); -__webpack_require__(500); -const factory_1 = __webpack_require__(501); -const fs_2 = __webpack_require__(306); -const is_1 = __webpack_require__(250); -const watchman_1 = tslib_1.__importDefault(__webpack_require__(327)); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -const createLogger = __webpack_require__(64); -const logger = createLogger('extensions'); -function loadJson(file) { - try { - let content = fs_1.default.readFileSync(file, 'utf8'); - return JSON.parse(content); - } - catch (e) { - return null; - } -} -// global local file native -class Extensions { - constructor() { - this.extensions = new Map(); - this.disabled = new Set(); - this._onDidLoadExtension = new vscode_languageserver_protocol_1.Emitter(); - this._onDidActiveExtension = new vscode_languageserver_protocol_1.Emitter(); - this._onDidUnloadExtension = new vscode_languageserver_protocol_1.Emitter(); - this._additionalSchemes = {}; - this.activated = false; - this.disposables = []; - this.ready = true; - this.onDidLoadExtension = this._onDidLoadExtension.event; - this.onDidActiveExtension = this._onDidActiveExtension.event; - this.onDidUnloadExtension = this._onDidUnloadExtension.event; - let folder = global.hasOwnProperty('__TEST__') ? path_1.default.join(__dirname, '__tests__') : process.env.COC_DATA_HOME; - let root = this.root = path_1.default.join(folder, 'extensions'); - if (!fs_1.default.existsSync(root)) { - mkdirp_1.default.sync(root); - } - let jsonFile = path_1.default.join(root, 'package.json'); - if (!fs_1.default.existsSync(jsonFile)) { - fs_1.default.writeFileSync(jsonFile, '{"dependencies":{}}', 'utf8'); - } - let filepath = path_1.default.join(root, 'db.json'); - this.db = new db_1.default(filepath); - } - async init() { - let data = loadJson(this.db.filepath) || {}; - let keys = Object.keys(data.extension || {}); - this.outputChannel = workspace_1.default.createOutputChannel('extensions'); - for (let key of keys) { - if (data.extension[key].disabled == true) { - this.disabled.add(key); - } - } - if (process.env.COC_NO_PLUGINS) - return; - let stats = await this.globalExtensionStats(); - let localStats = await this.localExtensionStats(stats.map(o => o.id)); - stats = stats.concat(localStats); - this.memos = new memos_1.default(path_1.default.resolve(this.root, '../memos.json')); - stats.map(stat => { - let extensionType = stat.isLocal ? types_1.ExtensionType.Local : types_1.ExtensionType.Global; - try { - this.createExtension(stat.root, stat.packageJSON, extensionType); - } - catch (e) { - logger.error(`Error on create ${stat.root}:`, e); - } - }); - await this.loadFileExtensions(); - commands_1.default.register({ - id: 'extensions.forceUpdateAll', - execute: async () => { - let arr = await this.cleanExtensions(); - logger.info(`Force update extensions: ${arr}`); - await this.installExtensions(arr); - } - }, false, 'remove all global extensions and install them'); - workspace_1.default.onDidRuntimePathChange(async (paths) => { - for (let p of paths) { - if (p && this.checkDirectory(p) === true) { - await this.loadExtension(p); - } - } - }, null, this.disposables); - } - async activateExtensions() { - this.activated = true; - for (let item of this.extensions.values()) { - let { id, packageJSON } = item.extension; - await this.setupActiveEvents(id, packageJSON); - } - // make sure workspace.env exists - let floatFactory = new floatFactory_1.default(workspace_1.default.nvim, workspace_1.default.env); - events_1.default.on('CursorMoved', debounce_1.debounce(async (bufnr) => { - if (this.installBuffer && bufnr == this.installBuffer.bufnr) { - let lnum = await workspace_1.default.nvim.call('line', ['.']); - let msgs = this.installBuffer.getMessages(lnum - 1); - let docs = msgs && msgs.length ? [{ content: msgs.join('\n'), filetype: 'txt' }] : []; - await floatFactory.show(docs); - } - }, 500)); - if (global.hasOwnProperty('__TEST__')) - return; - // check extensions need watch & install - this.checkExtensions().logError(); - let config = workspace_1.default.getConfiguration('coc.preferences'); - let interval = config.get('extensionUpdateCheck', 'never'); - let silent = config.get('silentAutoupdate', true); - if (interval != 'never') { - let now = new Date(); - let day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (interval == 'daily' ? 0 : 7)); - let ts = this.db.fetch('lastUpdate'); - if (ts && Number(ts) > day.getTime()) - return; - this.outputChannel.appendLine('Start auto update...'); - this.updateExtensions(false, silent).logError(); - } - } - async updateExtensions(sync, silent = false) { - if (!this.npm) - return; - let lockedList = await this.getLockedList(); - let stats = await this.globalExtensionStats(); - stats = stats.filter(o => ![...lockedList, ...this.disabled].includes(o.id)); - this.db.push('lastUpdate', Date.now()); - if (silent) { - workspace_1.default.showMessage('Updating extensions, checkout output:///extensions for details.', 'more'); - } - let installBuffer = this.installBuffer = new installBuffer_1.default(true, sync, silent ? this.outputChannel : undefined); - installBuffer.setExtensions(stats.map(o => o.id)); - await installBuffer.show(workspace_1.default.nvim); - let createInstaller = installer_1.createInstallerFactory(this.npm, this.modulesFolder); - let fn = (stat) => { - let { id } = stat; - installBuffer.startProgress([id]); - let url = stat.exotic ? stat.uri : null; - // msg => installBuffer.addMessage(id, msg) - let installer = createInstaller(id); - installer.on('message', (msg, isProgress) => { - installBuffer.addMessage(id, msg, isProgress); - }); - return installer.update(url).then(directory => { - installBuffer.finishProgress(id, true); - if (directory) { - this.loadExtension(directory).logError(); - } - }, err => { - installBuffer.addMessage(id, err.message); - installBuffer.finishProgress(id, false); - }); - }; - await util_2.concurrent(stats, fn, silent ? 1 : 3); - } - async checkExtensions() { - let { globalExtensions, watchExtensions } = workspace_1.default.env; - if (globalExtensions && globalExtensions.length) { - let names = this.filterGlobalExtensions(globalExtensions); - this.installExtensions(names).logError(); - } - // watch for changes - if (watchExtensions && watchExtensions.length) { - let watchmanPath = workspace_1.default.getWatchmanPath(); - if (!watchmanPath) - return; - for (let name of watchExtensions) { - let item = this.extensions.get(name); - if (item && item.directory) { - let directory = await util_1.promisify(fs_1.default.realpath)(item.directory); - let client = await watchman_1.default.createClient(watchmanPath, directory); - if (client) { - this.disposables.push(client); - client.subscribe('**/*.js', async () => { - await this.reloadExtension(name); - workspace_1.default.showMessage(`reloaded ${name}`); - }).then(disposable => { - this.disposables.push(disposable); - }, e => { - logger.error(e); - }); - } - } - } - } - } - /** - * Install extensions, can be called without initialize. - */ - async installExtensions(list = []) { - let { npm } = this; - if (!npm || !list.length) - return; - list = array_1.distinct(list); - let installBuffer = this.installBuffer = new installBuffer_1.default(); - installBuffer.setExtensions(list); - await installBuffer.show(workspace_1.default.nvim); - let createInstaller = installer_1.createInstallerFactory(this.npm, this.modulesFolder); - let fn = (key) => { - installBuffer.startProgress([key]); - let installer = createInstaller(key); - installer.on('message', (msg, isProgress) => { - installBuffer.addMessage(key, msg, isProgress); - }); - return installer.install().then(name => { - installBuffer.finishProgress(key, true); - let directory = path_1.default.join(this.modulesFolder, name); - this.loadExtension(directory).logError(); - }, err => { - installBuffer.addMessage(key, err.message); - installBuffer.finishProgress(key, false); - logger.error(`Error on install ${key}`, err); - }); - }; - await util_2.concurrent(list, fn); - } - /** - * Get list of extensions in package.json that not installed - */ - getMissingExtensions() { - let json = this.loadJson() || { dependencies: {} }; - let ids = []; - for (let key of Object.keys(json.dependencies)) { - let folder = path_1.default.join(this.modulesFolder, key); - if (!fs_1.default.existsSync(folder)) { - let val = json.dependencies[key]; - if (val.startsWith('http')) { - ids.push(val); - } - else { - ids.push(key); - } - } - } - return ids; - } - get npm() { - let npm = workspace_1.default.getConfiguration('npm').get('binPath', 'npm'); - npm = workspace_1.default.expand(npm); - for (let exe of [npm, 'yarnpkg', 'yarn', 'npm']) { - try { - let res = which_1.default.sync(exe); - return res; - } - catch (e) { - continue; - } - } - workspace_1.default.showMessage(`Can't find npm or yarn in your $PATH`, 'error'); - return null; - } - /** - * Get all loaded extensions. - */ - get all() { - return Array.from(this.extensions.values()).map(o => o.extension).filter(o => !this.isDisabled(o.id)); - } - getExtension(id) { - return this.extensions.get(id); - } - getExtensionState(id) { - let disabled = this.isDisabled(id); - if (disabled) - return 'disabled'; - let item = this.extensions.get(id); - if (!item) - return 'unknown'; - let { extension } = item; - return extension.isActive ? 'activated' : 'loaded'; - } - async getExtensionStates() { - let globalStats = await this.globalExtensionStats(); - let localStats = await this.localExtensionStats([]); - return globalStats.concat(localStats); - } - async getLockedList() { - let obj = await this.db.fetch('extension'); - obj = obj || {}; - return Object.keys(obj).filter(id => obj[id].locked === true); - } - async toggleLock(id) { - let key = `extension.${id}.locked`; - let locked = await this.db.fetch(key); - if (locked) { - this.db.delete(key); - } - else { - this.db.push(key, true); - } - } - async toggleExtension(id) { - let state = this.getExtensionState(id); - if (state == null) - return; - if (state == 'activated') { - await this.deactivate(id); - } - let key = `extension.${id}.disabled`; - this.db.push(key, state == 'disabled' ? false : true); - if (state != 'disabled') { - this.disabled.add(id); - await this.unloadExtension(id); - } - else { - this.disabled.delete(id); - let folder = path_1.default.join(this.modulesFolder, id); - if (fs_1.default.existsSync(folder)) { - await this.loadExtension(folder); - } - } - await util_2.wait(200); - } - async reloadExtension(id) { - let item = this.extensions.get(id); - if (!item) { - workspace_1.default.showMessage(`Extension ${id} not registered`, 'error'); - return; - } - if (item.type == types_1.ExtensionType.Internal) { - workspace_1.default.showMessage(`Can't reload internal extension "${item.id}"`, 'warning'); - return; - } - if (item.type == types_1.ExtensionType.SingleFile) { - await this.loadExtensionFile(item.filepath); - } - else if (item.directory) { - await this.loadExtension(item.directory); - } - else { - workspace_1.default.showMessage(`Can't reload extension ${item.id}`, 'warning'); - } - } - /** - * Unload & remove all global extensions, return removed extensions. - */ - async cleanExtensions() { - let dir = this.modulesFolder; - if (!fs_1.default.existsSync(dir)) - return []; - let ids = this.globalExtensions; - let res = []; - for (let id of ids) { - let directory = path_1.default.join(dir, id); - let stat = await util_1.promisify(fs_1.default.lstat)(directory); - if (!stat || (stat && stat.isSymbolicLink())) - continue; - await this.unloadExtension(id); - await util_1.promisify(rimraf_1.default)(directory, { glob: false }); - res.push(id); - } - return res; - } - async uninstallExtension(ids) { - try { - if (!ids.length) - return; - let [globals, filtered] = array_1.splitArray(ids, id => this.globalExtensions.includes(id)); - if (filtered.length) { - workspace_1.default.showMessage(`Extensions ${filtered} not global extensions, can't uninstall!`, 'warning'); - } - let json = this.loadJson() || { dependencies: {} }; - for (let id of globals) { - await this.unloadExtension(id); - delete json.dependencies[id]; - // remove directory - let folder = path_1.default.join(this.modulesFolder, id); - if (fs_1.default.existsSync(folder)) { - await util_1.promisify(rimraf_1.default)(folder, { glob: false }); - } - } - // update package.json - const sortedObj = { dependencies: {} }; - Object.keys(json.dependencies).sort().forEach(k => { - sortedObj.dependencies[k] = json.dependencies[k]; - }); - let jsonFile = path_1.default.join(this.root, 'package.json'); - fs_1.default.writeFileSync(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: 'utf8' }); - workspace_1.default.showMessage(`Removed: ${globals.join(' ')}`); - } - catch (e) { - workspace_1.default.showMessage(`Uninstall failed: ${e.message}`, 'error'); - } - } - isDisabled(id) { - return this.disabled.has(id); - } - has(id) { - return this.extensions.has(id); - } - isActivated(id) { - let item = this.extensions.get(id); - if (item && item.extension.isActive) { - return true; - } - return false; - } - /** - * Load extension from folder, folder should contains coc extension. - */ - async loadExtension(folder) { - try { - let parentFolder = path_1.default.dirname(folder); - let isLocal = path_1.default.normalize(parentFolder) != path_1.default.normalize(this.modulesFolder); - let jsonFile = path_1.default.join(folder, 'package.json'); - let packageJSON = JSON.parse(fs_1.default.readFileSync(jsonFile, 'utf8')); - let { name } = packageJSON; - if (this.isDisabled(name)) - return false; - // unload if loaded - await this.unloadExtension(name); - this.createExtension(folder, Object.freeze(packageJSON), isLocal ? types_1.ExtensionType.Local : types_1.ExtensionType.Global); - return true; - } - catch (e) { - workspace_1.default.showMessage(`Error on load extension from "${folder}": ${e.message}`, 'error'); - logger.error(`Error on load extension from ${folder}`, e); - return false; - } - } - async loadFileExtensions() { - if (!process.env.COC_VIMCONFIG) - return; - let folder = path_1.default.join(process.env.COC_VIMCONFIG, 'coc-extensions'); - if (!fs_1.default.existsSync(folder)) - return; - let files = await fs_2.readdirAsync(folder); - files = files.filter(f => f.endsWith('.js')); - for (let file of files) { - await this.loadExtensionFile(path_1.default.join(folder, file)); - } - let watchmanPath = workspace_1.default.getWatchmanPath(); - if (!watchmanPath) - return; - let client = await watchman_1.default.createClient(watchmanPath, folder); - if (!client) - return; - this.disposables.push(client); - client.subscribe('*.js', async ({ root, files }) => { - files = files.filter(f => f.type == 'f'); - for (let file of files) { - let id = `single-` + path_1.default.basename(file.name, 'js'); - if (file.exists) { - let filepath = path_1.default.join(root, file.name); - await this.loadExtensionFile(filepath); - } - else { - await this.unloadExtension(id); - } - } - }).then(disposable => { - this.disposables.push(disposable); - }, e => { - logger.error(e); - }); - } - /** - * Load single javascript file as extension. - */ - async loadExtensionFile(filepath) { - let filename = path_1.default.basename(filepath); - let name = 'single-' + path_1.default.basename(filepath, '.js'); - if (this.isDisabled(name)) - return; - let root = path_1.default.dirname(filepath); - let packageJSON = { - name, main: filename, engines: { coc: '^0.0.79' } - }; - await this.unloadExtension(name); - this.createExtension(root, packageJSON, types_1.ExtensionType.SingleFile); - } - /** - * Activate extension, throw error if disabled or not exists - * Returns true if extension successfully activated. - */ - async activate(id) { - if (this.isDisabled(id)) { - throw new Error(`Extension ${id} is disabled!`); - } - let item = this.extensions.get(id); - if (!item) { - throw new Error(`Extension ${id} not registered!`); - } - let { extension } = item; - if (extension.isActive) - return true; - await Promise.resolve(extension.activate()); - if (extension.isActive) { - this._onDidActiveExtension.fire(extension); - return true; - } - return false; - } - async deactivate(id) { - let item = this.extensions.get(id); - if (!item) - return false; - await Promise.resolve(item.deactivate()); - return true; - } - async call(id, method, args) { - let item = this.extensions.get(id); - if (!item) - throw new Error(`extension ${id} not registered`); - let { extension } = item; - if (!extension.isActive) { - await this.activate(id); - } - let { exports } = extension; - if (!exports || !exports.hasOwnProperty(method)) { - throw new Error(`method ${method} not found on extension ${id}`); - } - return await Promise.resolve(exports[method].apply(null, args)); - } - getExtensionApi(id) { - let item = this.extensions.get(id); - if (!item) - return null; - let { extension } = item; - return extension.isActive ? extension.exports : null; - } - registerExtension(extension, deactivate) { - let { id, packageJSON } = extension; - this.extensions.set(id, { id, type: types_1.ExtensionType.Internal, extension, deactivate, isLocal: true }); - let { contributes } = packageJSON; - if (contributes) { - let { configuration } = contributes; - if (configuration && configuration.properties) { - let { properties } = configuration; - let props = {}; - for (let key of Object.keys(properties)) { - let val = properties[key].default; - if (val != null) - props[key] = val; - } - workspace_1.default.configurations.extendsDefaults(props); - } - } - this._onDidLoadExtension.fire(extension); - this.setupActiveEvents(id, packageJSON).logError(); - } - get globalExtensions() { - let json = this.loadJson(); - if (!json || !json.dependencies) - return []; - return Object.keys(json.dependencies); - } - async globalExtensionStats() { - let json = this.loadJson(); - if (!json || !json.dependencies) - return []; - let { modulesFolder } = this; - let res = await Promise.all(Object.keys(json.dependencies).map(key => new Promise(async (resolve) => { - try { - let val = json.dependencies[key]; - let root = path_1.default.join(modulesFolder, key); - let res = this.checkDirectory(root); - if (res instanceof Error) { - workspace_1.default.showMessage(`Unable to load global extension at ${root}: ${res.message}`, 'error'); - logger.error(`Error on load ${root}`, res); - return resolve(null); - } - let content = await fs_2.readFile(path_1.default.join(root, 'package.json'), 'utf8'); - root = await fs_2.realpathAsync(root); - let obj = JSON.parse(content); - let version = obj ? obj.version || '' : ''; - let description = obj ? obj.description || '' : ''; - let uri = isuri_1.default.isValid(val) ? val : ''; - resolve({ - id: key, - isLocal: false, - version, - description, - exotic: /^https?:/.test(val), - uri: uri.replace(/\.git(#master)?$/, ''), - root, - state: this.getExtensionState(key), - packageJSON: Object.freeze(obj) - }); - } - catch (e) { - logger.error(e); - resolve(null); - } - }))); - return res.filter(info => info != null); - } - async localExtensionStats(excludes) { - let runtimepath = await workspace_1.default.nvim.eval('&runtimepath'); - let paths = runtimepath.split(','); - let res = await Promise.all(paths.map(root => new Promise(async (resolve) => { - try { - let res = this.checkDirectory(root); - if (res !== true) - return resolve(null); - let jsonFile = path_1.default.join(root, 'package.json'); - let content = await fs_2.readFile(jsonFile, 'utf8'); - let obj = JSON.parse(content); - let exist = this.extensions.get(obj.name); - if (exist && !exist.isLocal) { - logger.info(`Extension "${obj.name}" in runtimepath already loaded.`); - return resolve(null); - } - if (excludes.includes(obj.name)) { - logger.info(`Skipped load vim plugin from "${root}", "${obj.name}" already global extension.`); - return resolve(null); - } - let version = obj ? obj.version || '' : ''; - let description = obj ? obj.description || '' : ''; - resolve({ - id: obj.name, - isLocal: true, - version, - description, - exotic: false, - root, - state: this.getExtensionState(obj.name), - packageJSON: Object.freeze(obj) - }); - } - catch (e) { - logger.error(e); - resolve(null); - } - }))); - return res.filter(info => info != null); - } - loadJson() { - let { root } = this; - let jsonFile = path_1.default.join(root, 'package.json'); - if (!fs_1.default.existsSync(jsonFile)) - return null; - return loadJson(jsonFile); - } - get schemes() { - return this._additionalSchemes; - } - addSchemeProperty(key, def) { - this._additionalSchemes[key] = def; - workspace_1.default.configurations.extendsDefaults({ [key]: def.default }); - } - async setupActiveEvents(id, packageJSON) { - let { activationEvents } = packageJSON; - if (!this.canActivate(id)) - return; - if (!activationEvents || Array.isArray(activationEvents) && activationEvents.includes('*')) { - await this.activate(id).catch(e => { - workspace_1.default.showMessage(`Error on activate extension ${id}: ${e.message}`); - logger.error(`Error on activate extension ${id}`, e); - }); - return; - } - let disposables = []; - let active = () => { - util_2.disposeAll(disposables); - return new Promise(resolve => { - if (!this.canActivate(id)) - return resolve(); - let timer = setTimeout(() => { - logger.warn(`Extension ${id} activate cost more than 1s`); - resolve(); - }, 1000); - this.activate(id).then(() => { - clearTimeout(timer); - resolve(); - }, e => { - clearTimeout(timer); - workspace_1.default.showMessage(`Error on activate extension ${id}: ${e.message}`); - logger.error(`Error on activate extension ${id}`, e); - resolve(); - }); - }); - }; - for (let eventName of activationEvents) { - let parts = eventName.split(':'); - let ev = parts[0]; - if (ev == 'onLanguage') { - if (workspace_1.default.filetypes.has(parts[1])) { - await active(); - return; - } - workspace_1.default.onDidOpenTextDocument(document => { - if (document.languageId == parts[1]) { - active().logError(); - } - }, null, disposables); - } - else if (ev == 'onCommand') { - events_1.default.on('Command', command => { - if (command == parts[1]) { - active().logError(); - // wait for service ready - return new Promise(resolve => { - setTimeout(resolve, 500); - }); - } - }, null, disposables); - } - else if (ev == 'workspaceContains') { - let check = async () => { - let folders = workspace_1.default.workspaceFolders.map(o => vscode_uri_1.URI.parse(o.uri).fsPath); - for (let folder of folders) { - if (fs_2.inDirectory(folder, parts[1].split(/\s+/))) { - await active(); - return true; - } - } - }; - let res = await check(); - if (res) - return; - workspace_1.default.onDidChangeWorkspaceFolders(check, null, disposables); - } - else if (ev == 'onFileSystem') { - for (let doc of workspace_1.default.documents) { - let u = vscode_uri_1.URI.parse(doc.uri); - if (u.scheme == parts[1]) { - await active(); - return; - } - } - workspace_1.default.onDidOpenTextDocument(document => { - let u = vscode_uri_1.URI.parse(document.uri); - if (u.scheme == parts[1]) { - active().logError(); - } - }, null, disposables); - } - else { - workspace_1.default.showMessage(`Unsupported event ${eventName} of ${id}`, 'error'); - } - } - } - createExtension(root, packageJSON, type) { - let id = packageJSON.name; - let isActive = false; - let exports = null; - let filename = path_1.default.join(root, packageJSON.main || 'index.js'); - let ext; - let subscriptions = []; - let extension = { - activate: async () => { - if (isActive) - return exports; - let context = { - subscriptions, - extensionPath: root, - globalState: this.memos.createMemento(`${id}|global`), - workspaceState: this.memos.createMemento(`${id}|${workspace_1.default.rootPath}`), - asAbsolutePath: relativePath => path_1.default.join(root, relativePath), - storagePath: path_1.default.join(this.root, `${id}-data`), - logger: createLogger(id) - }; - isActive = true; - if (!ext) { - try { - let isEmpty = !(packageJSON.engines || {}).hasOwnProperty('coc'); - ext = factory_1.createExtension(id, filename, isEmpty); - } - catch (e) { - logger.error(`Error on createExtension ${id} from ${filename}`, e); - return; - } - } - try { - exports = await Promise.resolve(ext.activate(context)); - logger.debug('activate:', id); - } - catch (e) { - isActive = false; - logger.error(`Error on active extension ${id}: ${e.stack}`, e); - } - return exports; - } - }; - Object.defineProperties(extension, { - id: { - get: () => id - }, - packageJSON: { - get: () => packageJSON - }, - extensionPath: { - get: () => root - }, - isActive: { - get: () => isActive - }, - exports: { - get: () => exports - } - }); - this.extensions.set(id, { - id, - type, - isLocal: type == types_1.ExtensionType.Local, - extension, - directory: root, - filepath: filename, - deactivate: () => { - if (!isActive) - return; - isActive = false; - util_2.disposeAll(subscriptions); - subscriptions.splice(0, subscriptions.length); - subscriptions = []; - if (ext && ext.deactivate) { - try { - return Promise.resolve(ext.deactivate()).catch(e => { - logger.error(`Error on ${id} deactivate: `, e); - }); - } - catch (e) { - logger.error(`Error on ${id} deactivate: `, e); - } - } - } - }); - let { contributes } = packageJSON; - if (contributes) { - let { configuration, rootPatterns, commands } = contributes; - if (configuration && configuration.properties) { - let { properties } = configuration; - let props = {}; - for (let key of Object.keys(properties)) { - let val = properties[key].default; - if (val != null) - props[key] = val; - } - workspace_1.default.configurations.extendsDefaults(props); - } - if (rootPatterns && rootPatterns.length) { - for (let item of rootPatterns) { - workspace_1.default.addRootPattern(item.filetype, item.patterns); - } - } - if (commands && commands.length) { - for (let cmd of commands) { - commands_1.default.titles.set(cmd.command, cmd.title); - } - } - } - this._onDidLoadExtension.fire(extension); - if (this.activated) { - this.setupActiveEvents(id, packageJSON).logError(); - } - } - // extension must exists as folder and in package.json - filterGlobalExtensions(names) { - names = names.map(s => s.replace(/@.*$/, '')); - let filtered = names.filter(name => !this.disabled.has(name)); - filtered = filtered.filter(name => !this.extensions.has(name)); - let json = this.loadJson(); - let urls = []; - let exists = []; - if (json && json.dependencies) { - for (let key of Object.keys(json.dependencies)) { - let val = json.dependencies[key]; - if (typeof val !== 'string') - continue; - if (fs_1.default.existsSync(path_1.default.join(this.modulesFolder, key, 'package.json'))) { - exists.push(key); - if (/^https?:/.test(val)) { - urls.push(val); - } - } - } - } - filtered = filtered.filter(str => { - if (/^https?:/.test(str)) - return !urls.some(url => url.startsWith(str)); - return !exists.includes(str); - }); - return filtered; - } - get modulesFolder() { - return path_1.default.join(this.root, global.hasOwnProperty('__TEST__') ? '' : 'node_modules'); - } - canActivate(id) { - return !this.disabled.has(id) && this.extensions.has(id); - } - /** - * Deactive & unregist extension - */ - async unloadExtension(id) { - let item = this.extensions.get(id); - if (item) { - await this.deactivate(id); - this.extensions.delete(id); - this._onDidUnloadExtension.fire(id); - } - } - /** - * Check if folder contains extension, return Error - */ - checkDirectory(folder) { - try { - let jsonFile = path_1.default.join(folder, 'package.json'); - if (!fs_1.default.existsSync(jsonFile)) - throw new Error('package.json not found'); - let packageJSON = JSON.parse(fs_1.default.readFileSync(jsonFile, 'utf8')); - let { name, engines, main } = packageJSON; - if (!name || !engines) - throw new Error(`can't find name & engines in package.json`); - if (!engines || !is_1.objectLiteral(engines)) { - throw new Error(`invalid engines in ${jsonFile}`); - } - if (main && !fs_1.default.existsSync(path_1.default.join(folder, main))) { - throw new Error(`main file ${main} not found, you may need to build the project.`); - } - let keys = Object.keys(engines); - if (!keys.includes('coc') && !keys.includes('vscode')) { - throw new Error(`Engines in package.json doesn't have coc or vscode`); - } - if (keys.includes('coc')) { - let required = engines['coc'].replace(/^\^/, '>='); - if (!semver_1.default.satisfies(workspace_1.default.version, required)) { - throw new Error(`Please update coc.nvim, ${packageJSON.name} requires coc.nvim ${engines['coc']}`); - } - } - return true; - } - catch (e) { - return e; - } - } - dispose() { - util_2.disposeAll(this.disposables); - } -} -exports.Extensions = Extensions; -exports.default = new Extensions(); -//# sourceMappingURL=extensions.js.map - -/***/ }), -/* 343 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.State = void 0; -const events_1 = __webpack_require__(198); -const status_1 = __webpack_require__(322); -const logger = __webpack_require__(64)('model-installBuffer'); -var State; -(function (State) { - State[State["Waiting"] = 0] = "Waiting"; - State[State["Faild"] = 1] = "Faild"; - State[State["Progressing"] = 2] = "Progressing"; - State[State["Success"] = 3] = "Success"; -})(State = exports.State || (exports.State = {})); -class InstallBuffer extends events_1.EventEmitter { - constructor(isUpdate = false, isSync = false, channel = undefined) { - super(); - this.isUpdate = isUpdate; - this.isSync = isSync; - this.channel = channel; - this.statMap = new Map(); - this.messagesMap = new Map(); - this.names = []; - } - setExtensions(names) { - this.statMap.clear(); - this.names = names; - for (let name of names) { - this.statMap.set(name, State.Waiting); - } - } - addMessage(name, msg, isProgress = false) { - if (isProgress && this.channel) - return; - let lines = this.messagesMap.get(name) || []; - this.messagesMap.set(name, lines.concat(msg.trim().split(/\r?\n/))); - if (this.channel) - this.channel.appendLine(`[${name}] ${msg}`); - } - startProgress(names) { - for (let name of names) { - this.statMap.set(name, State.Progressing); - } - } - finishProgress(name, succeed = true) { - if (this.channel) { - if (succeed) { - this.channel.appendLine(`[${name}] install succeed!`); - } - else { - this.channel.appendLine(`[${name}] install failed!`); - } - } - this.statMap.set(name, succeed ? State.Success : State.Faild); - } - get remains() { - let count = 0; - for (let name of this.names) { - let stat = this.statMap.get(name); - if (![State.Success, State.Faild].includes(stat)) { - count = count + 1; - } - } - return count; - } - getLines() { - let lines = []; - for (let name of this.names) { - let state = this.statMap.get(name); - let processText = '*'; - switch (state) { - case State.Progressing: { - let d = new Date(); - let idx = Math.floor(d.getMilliseconds() / 100); - processText = status_1.frames[idx]; - break; - } - case State.Faild: - processText = '✗'; - break; - case State.Success: - processText = '✓'; - break; - } - let msgs = this.messagesMap.get(name) || []; - lines.push(`- ${processText} ${name} ${msgs.length ? msgs[msgs.length - 1] : ''}`); - } - return lines; - } - getMessages(line) { - if (line <= 1) - return []; - let name = this.names[line - 2]; - if (!name) - return []; - return this.messagesMap.get(name); - } - // draw frame - draw(nvim, buffer) { - let { remains } = this; - let first = remains == 0 ? `${this.isUpdate ? 'Update' : 'Install'} finished` : `Installing, ${remains} remains...`; - let lines = [first, '', ...this.getLines()]; - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }, true); - if (remains == 0 && this.interval) { - clearInterval(this.interval); - this.interval = null; - } - if (process.env.VIM_NODE_RPC) { - nvim.command('redraw', true); - } - } - highlight(nvim) { - nvim.call('matchadd', ['CocListFgCyan', '^\\-\\s\\zs\\*'], true); - nvim.call('matchadd', ['CocListFgGreen', '^\\-\\s\\zs✓'], true); - nvim.call('matchadd', ['CocListFgRed', '^\\-\\s\\zs✗'], true); - nvim.call('matchadd', ['CocListFgYellow', '^-.\\{3\\}\\zs\\S\\+'], true); - } - async show(nvim) { - let { isSync } = this; - if (this.channel) - return; - nvim.pauseNotification(); - nvim.command(isSync ? 'enew' : 'vs +enew', true); - nvim.call('bufnr', ['%'], true); - nvim.command('setl buftype=nofile bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1', true); - if (!isSync) { - nvim.command('nnoremap q :q', true); - } - this.highlight(nvim); - let res = await nvim.resumeNotification(); - let bufnr = res && res[1] == null ? res[0][1] : null; - if (!bufnr) - return; - this.bufnr = bufnr; - let buffer = nvim.createBuffer(bufnr); - this.interval = setInterval(() => { - this.draw(nvim, buffer); - }, 100); - } - dispose() { - if (this.interval) { - clearInterval(this.interval); - } - } -} -exports.default = InstallBuffer; -//# sourceMappingURL=installBuffer.js.map - -/***/ }), -/* 344 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createInstallerFactory = exports.Installer = void 0; -const tslib_1 = __webpack_require__(65); -const events_1 = __webpack_require__(198); -const child_process_1 = __webpack_require__(239); -const readline_1 = tslib_1.__importDefault(__webpack_require__(206)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -const mv_1 = tslib_1.__importDefault(__webpack_require__(345)); -const os_1 = tslib_1.__importDefault(__webpack_require__(76)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const rc_1 = tslib_1.__importDefault(__webpack_require__(352)); -const semver_1 = tslib_1.__importDefault(__webpack_require__(1)); -const util_1 = __webpack_require__(74); -const workspace_1 = tslib_1.__importDefault(__webpack_require__(269)); -const download_1 = tslib_1.__importDefault(__webpack_require__(358)); -const fetch_1 = tslib_1.__importDefault(__webpack_require__(487)); -const rimraf_1 = tslib_1.__importDefault(__webpack_require__(279)); -const fs_2 = __webpack_require__(306); -const logger = __webpack_require__(64)('model-installer'); -function registryUrl(scope = 'coc.nvim') { - const result = rc_1.default('npm', { registry: 'https://registry.npmjs.org/' }); - const registry = result[`${scope}:registry`] || result.config_registry || result.registry; - return registry.endsWith('/') ? registry : registry + '/'; -} -class Installer extends events_1.EventEmitter { - constructor(root, npm, - // could be url or name@version or name - def) { - super(); - this.root = root; - this.npm = npm; - this.def = def; - if (!fs_1.default.existsSync(root)) - mkdirp_1.default.sync(root); - if (/^https?:/.test(def)) { - this.url = def; - } - else { - if (def.includes('@')) { - let [name, version] = def.split('@', 2); - this.name = name; - this.version = version; - } - else { - this.name = def; - } - } - } - async install() { - this.log(`Using npm from: ${this.npm}`); - let info = await this.getInfo(); - logger.info(`Fetched info of ${this.def}`, info); - let { name } = info; - let required = info['engines.coc'] ? info['engines.coc'].replace(/^\^/, '>=') : ''; - if (required && !semver_1.default.satisfies(workspace_1.default.version, required)) { - throw new Error(`${name} ${info.version} requires coc.nvim >= ${required}, please update coc.nvim.`); - } - await this.doInstall(info); - return name; - } - async update(url) { - this.url = url; - let folder = path_1.default.join(this.root, this.name); - let stat = await util_1.promisify(fs_1.default.lstat)(folder); - if (stat.isSymbolicLink()) { - this.log(`Skipped update for symbol link`); - return; - } - let version; - if (fs_1.default.existsSync(path_1.default.join(folder, 'package.json'))) { - let content = await util_1.promisify(fs_1.default.readFile)(path_1.default.join(folder, 'package.json'), 'utf8'); - version = JSON.parse(content).version; - } - this.log(`Using npm from: ${this.npm}`); - let info = await this.getInfo(); - if (version && info.version && semver_1.default.gte(version, info.version)) { - this.log(`Current version ${version} is up to date.`); - return; - } - let required = info['engines.coc'] ? info['engines.coc'].replace(/^\^/, '>=') : ''; - if (required && !semver_1.default.satisfies(workspace_1.default.version, required)) { - throw new Error(`${info.version} requires coc.nvim ${required}, please update coc.nvim.`); - } - await this.doInstall(info); - let jsonFile = path_1.default.join(this.root, info.name, 'package.json'); - if (fs_1.default.existsSync(jsonFile)) { - this.log(`Updated to v${info.version}`); - return path_1.default.dirname(jsonFile); - } - else { - throw new Error(`Package.json not found: ${jsonFile}`); - } - } - async doInstall(info) { - let folder = path_1.default.join(this.root, info.name); - if (fs_1.default.existsSync(folder)) { - let stat = fs_1.default.statSync(folder); - if (!stat.isDirectory()) { - this.log(`${folder} is not directory skipped install`); - return; - } - } - let tmpFolder = await util_1.promisify(fs_1.default.mkdtemp)(path_1.default.join(os_1.default.tmpdir(), `${info.name}-`)); - let url = info['dist.tarball']; - this.log(`Downloading from ${url}`); - await download_1.default(url, { dest: tmpFolder, onProgress: p => this.log(`Download progress ${p}%`, true), extract: 'untar' }); - this.log(`Extension download at ${tmpFolder}`); - let content = await util_1.promisify(fs_1.default.readFile)(path_1.default.join(tmpFolder, 'package.json'), 'utf8'); - let { dependencies } = JSON.parse(content); - if (dependencies && Object.keys(dependencies).length) { - let p = new Promise((resolve, reject) => { - let args = ['install', '--ignore-scripts', '--no-lockfile', '--production']; - if (url.startsWith('https://github.com')) { - args = ['install']; - } - if (this.npm.endsWith('npm')) { - args.push('--legacy-peer-deps'); - } - this.log(`Installing dependencies by: ${this.npm} ${args.join(' ')}.`); - const child = child_process_1.spawn(this.npm, args, { - cwd: tmpFolder, - }); - const rl = readline_1.default.createInterface({ - input: child.stdout - }); - rl.on('line', line => { - this.log(`[npm] ${line}`, true); - }); - child.stderr.setEncoding('utf8'); - child.stdout.setEncoding('utf8'); - child.on('error', reject); - let err = ''; - child.stderr.on('data', data => { - err += data; - }); - child.on('exit', code => { - if (code) { - if (err) - this.log(err); - reject(new Error(`${this.npm} install exited with ${code}`)); - return; - } - resolve(); - }); - }); - await p; - } - let jsonFile = path_1.default.resolve(this.root, global.hasOwnProperty('__TEST__') ? '' : '..', 'package.json'); - let obj = JSON.parse(fs_1.default.readFileSync(jsonFile, 'utf8')); - obj.dependencies = obj.dependencies || {}; - if (this.url) { - obj.dependencies[info.name] = this.url; - } - else { - obj.dependencies[info.name] = '>=' + info.version; - } - const sortedObj = { dependencies: {} }; - Object.keys(obj.dependencies).sort().forEach(k => { - sortedObj.dependencies[k] = obj.dependencies[k]; - }); - let stat = await fs_2.statAsync(folder); - if (stat) { - if (stat.isDirectory()) { - rimraf_1.default.sync(folder, { glob: false }); - } - else { - fs_1.default.unlinkSync(folder); - } - } - await util_1.promisify(mv_1.default)(tmpFolder, folder, { mkdirp: true, clobber: true }); - fs_1.default.writeFileSync(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: 'utf8' }); - this.log(`Update package.json at ${jsonFile}`); - this.log(`Installed extension ${this.name}@${info.version} at ${folder}`); - } - async getInfo() { - if (this.url) - return await this.getInfoFromUri(); - let registry = registryUrl(); - this.log(`Get info from ${registry}`); - let res = await fetch_1.default(registry + this.name, { timeout: 10000 }); - if (!this.version) - this.version = res['dist-tags']['latest']; - let obj = res['versions'][this.version]; - if (!obj) - throw new Error(`${this.def} doesn't exists in ${registry}.`); - let requiredVersion = obj['engines'] && obj['engines']['coc']; - if (!requiredVersion) { - throw new Error(`${this.def} is not valid coc extension, "engines" field with coc property required.`); - } - return { - 'dist.tarball': obj['dist']['tarball'], - 'engines.coc': requiredVersion, - version: obj['version'], - name: res.name - }; - } - async getInfoFromUri() { - let { url } = this; - if (!url.includes('github.com')) { - throw new Error(`"${url}" is not supported, coc.nvim support github.com only`); - } - url = url.replace(/\/$/, ''); - let fileUrl = url.replace('github.com', 'raw.githubusercontent.com') + '/master/package.json'; - this.log(`Get info from ${fileUrl}`); - let content = await fetch_1.default(fileUrl, { timeout: 10000 }); - let obj = typeof content == 'string' ? JSON.parse(content) : content; - this.name = obj.name; - return { - 'dist.tarball': `${url}/archive/master.tar.gz`, - 'engines.coc': obj['engines'] ? obj['engines']['coc'] : null, - name: obj.name, - version: obj.version - }; - } - log(msg, isProgress = false) { - logger.info(msg); - this.emit('message', msg, isProgress); - } -} -exports.Installer = Installer; -function createInstallerFactory(npm, root) { - return (def) => new Installer(root, npm, def); -} -exports.createInstallerFactory = createInstallerFactory; -//# sourceMappingURL=installer.js.map - -/***/ }), -/* 345 */ -/***/ (function(module, exports, __webpack_require__) { - -var fs = __webpack_require__(66); -var ncp = __webpack_require__(346).ncp; -var path = __webpack_require__(82); -var rimraf = __webpack_require__(347); -var mkdirp = __webpack_require__(351); - -module.exports = mv; - -function mv(source, dest, options, cb){ - if (typeof options === 'function') { - cb = options; - options = {}; - } - var shouldMkdirp = !!options.mkdirp; - var clobber = options.clobber !== false; - var limit = options.limit || 16; - - if (shouldMkdirp) { - mkdirs(); - } else { - doRename(); - } - - function mkdirs() { - mkdirp(path.dirname(dest), function(err) { - if (err) return cb(err); - doRename(); - }); - } - - function doRename() { - if (clobber) { - fs.rename(source, dest, function(err) { - if (!err) return cb(); - if (err.code !== 'EXDEV') return cb(err); - moveFileAcrossDevice(source, dest, clobber, limit, cb); - }); - } else { - fs.link(source, dest, function(err) { - if (err) { - if (err.code === 'EXDEV') { - moveFileAcrossDevice(source, dest, clobber, limit, cb); - return; - } - if (err.code === 'EISDIR' || err.code === 'EPERM') { - moveDirAcrossDevice(source, dest, clobber, limit, cb); - return; - } - cb(err); - return; - } - fs.unlink(source, cb); - }); - } - } -} - -function moveFileAcrossDevice(source, dest, clobber, limit, cb) { - var outFlags = clobber ? 'w' : 'wx'; - var ins = fs.createReadStream(source); - var outs = fs.createWriteStream(dest, {flags: outFlags}); - ins.on('error', function(err){ - ins.destroy(); - outs.destroy(); - outs.removeListener('close', onClose); - if (err.code === 'EISDIR' || err.code === 'EPERM') { - moveDirAcrossDevice(source, dest, clobber, limit, cb); - } else { - cb(err); - } - }); - outs.on('error', function(err){ - ins.destroy(); - outs.destroy(); - outs.removeListener('close', onClose); - cb(err); - }); - outs.once('close', onClose); - ins.pipe(outs); - function onClose(){ - fs.unlink(source, cb); - } -} - -function moveDirAcrossDevice(source, dest, clobber, limit, cb) { - var options = { - stopOnErr: true, - clobber: false, - limit: limit, - }; - if (clobber) { - rimraf(dest, { disableGlob: true }, function(err) { - if (err) return cb(err); - startNcp(); - }); - } else { - startNcp(); - } - function startNcp() { - ncp(source, dest, options, function(errList) { - if (errList) return cb(errList[0]); - rimraf(source, { disableGlob: true }, cb); - }); - } -} - - -/***/ }), -/* 346 */ -/***/ (function(module, exports, __webpack_require__) { - -var fs = __webpack_require__(66), - path = __webpack_require__(82); - -module.exports = ncp; -ncp.ncp = ncp; - -function ncp (source, dest, options, callback) { - var cback = callback; - - if (!callback) { - cback = options; - options = {}; - } - - var basePath = process.cwd(), - currentPath = path.resolve(basePath, source), - targetPath = path.resolve(basePath, dest), - filter = options.filter, - rename = options.rename, - transform = options.transform, - clobber = options.clobber !== false, - modified = options.modified, - dereference = options.dereference, - errs = null, - started = 0, - finished = 0, - running = 0, - limit = options.limit || ncp.limit || 16; - - limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; - - startCopy(currentPath); - - function startCopy(source) { - started++; - if (filter) { - if (filter instanceof RegExp) { - if (!filter.test(source)) { - return cb(true); - } - } - else if (typeof filter === 'function') { - if (!filter(source)) { - return cb(true); - } - } - } - return getStats(source); - } - - function getStats(source) { - var stat = dereference ? fs.stat : fs.lstat; - if (running >= limit) { - return setImmediate(function () { - getStats(source); - }); - } - running++; - stat(source, function (err, stats) { - var item = {}; - if (err) { - return onError(err); - } - - // We need to get the mode from the stats object and preserve it. - item.name = source; - item.mode = stats.mode; - item.mtime = stats.mtime; //modified time - item.atime = stats.atime; //access time - - if (stats.isDirectory()) { - return onDir(item); - } - else if (stats.isFile()) { - return onFile(item); - } - else if (stats.isSymbolicLink()) { - // Symlinks don't really need to know about the mode. - return onLink(source); - } - }); - } - - function onFile(file) { - var target = file.name.replace(currentPath, targetPath); - if(rename) { - target = rename(target); - } - isWritable(target, function (writable) { - if (writable) { - return copyFile(file, target); - } - if(clobber) { - rmFile(target, function () { - copyFile(file, target); - }); - } - if (modified) { - var stat = dereference ? fs.stat : fs.lstat; - stat(target, function(err, stats) { - //if souce modified time greater to target modified time copy file - if (file.mtime.getTime()>stats.mtime.getTime()) - copyFile(file, target); - else return cb(); - }); - } - else { - return cb(); - } - }); - } - - function copyFile(file, target) { - var readStream = fs.createReadStream(file.name), - writeStream = fs.createWriteStream(target, { mode: file.mode }); - - readStream.on('error', onError); - writeStream.on('error', onError); - - if(transform) { - transform(readStream, writeStream, file); - } else { - writeStream.on('open', function() { - readStream.pipe(writeStream); - }); - } - writeStream.once('finish', function() { - if (modified) { - //target file modified date sync. - fs.utimesSync(target, file.atime, file.mtime); - cb(); - } - else cb(); - }); - } - - function rmFile(file, done) { - fs.unlink(file, function (err) { - if (err) { - return onError(err); - } - return done(); - }); - } - - function onDir(dir) { - var target = dir.name.replace(currentPath, targetPath); - isWritable(target, function (writable) { - if (writable) { - return mkDir(dir, target); - } - copyDir(dir.name); - }); - } - - function mkDir(dir, target) { - fs.mkdir(target, dir.mode, function (err) { - if (err) { - return onError(err); - } - copyDir(dir.name); - }); - } - - function copyDir(dir) { - fs.readdir(dir, function (err, items) { - if (err) { - return onError(err); - } - items.forEach(function (item) { - startCopy(path.join(dir, item)); - }); - return cb(); - }); - } - - function onLink(link) { - var target = link.replace(currentPath, targetPath); - fs.readlink(link, function (err, resolvedPath) { - if (err) { - return onError(err); - } - checkLink(resolvedPath, target); - }); - } - - function checkLink(resolvedPath, target) { - if (dereference) { - resolvedPath = path.resolve(basePath, resolvedPath); - } - isWritable(target, function (writable) { - if (writable) { - return makeLink(resolvedPath, target); - } - fs.readlink(target, function (err, targetDest) { - if (err) { - return onError(err); - } - if (dereference) { - targetDest = path.resolve(basePath, targetDest); - } - if (targetDest === resolvedPath) { - return cb(); - } - return rmFile(target, function () { - makeLink(resolvedPath, target); - }); - }); - }); - } - - function makeLink(linkPath, target) { - fs.symlink(linkPath, target, function (err) { - if (err) { - return onError(err); - } - return cb(); - }); - } - - function isWritable(path, done) { - fs.lstat(path, function (err) { - if (err) { - if (err.code === 'ENOENT') return done(true); - return done(false); - } - return done(false); - }); - } - - function onError(err) { - if (options.stopOnError) { - return cback(err); - } - else if (!errs && options.errs) { - errs = fs.createWriteStream(options.errs); - } - else if (!errs) { - errs = []; - } - if (typeof errs.write === 'undefined') { - errs.push(err); - } - else { - errs.write(err.stack + '\n\n'); - } - return cb(); - } - - function cb(skipped) { - if (!skipped) running--; - finished++; - if ((started === finished) && (running === 0)) { - if (cback !== undefined ) { - return errs ? cback(errs) : cback(null); - } - } - } -} - - - - -/***/ }), -/* 347 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = rimraf -rimraf.sync = rimrafSync - -var assert = __webpack_require__(108) -var path = __webpack_require__(82) -var fs = __webpack_require__(66) -var glob = __webpack_require__(348) - -var globOpts = { - nosort: true, - nocomment: true, - nonegate: true, - silent: true -} - -// for EMFILE handling -var timeout = 0 - -var isWindows = (process.platform === "win32") - -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - options.disableGlob = options.disableGlob || false -} - -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - - defaults(options) - - var busyTries = 0 - var errState = null - var n = 0 - - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) - - fs.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) - - glob(p, globOpts, afterGlob) - }) - - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } - - function afterGlob (er, results) { - if (er) - return cb(er) - - n = results.length - if (n === 0) - return cb() - - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } - - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } - - // already gone - if (er.code === "ENOENT") er = null - } - - timeout = 0 - next(er) - }) - }) - } -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) - - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) - - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) -} - -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) - - options.chmod(p, 666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} - -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) - - try { - options.chmodSync(p, 666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } - - try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } - - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} - -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - var results - - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - fs.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, globOpts) - } - } - - if (!results.length) - return - - for (var i = 0; i < results.length; i++) { - var p = results[i] - - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er - rmdirSync(p, options, er) - } - } -} - -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) - options.rmdirSync(p, options) -} - - -/***/ }), -/* 348 */ -/***/ (function(module, exports, __webpack_require__) { - -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - -module.exports = glob - -var fs = __webpack_require__(66) -var minimatch = __webpack_require__(283) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(287) -var EE = __webpack_require__(198).EventEmitter -var path = __webpack_require__(82) -var assert = __webpack_require__(108) -var isAbsolute = __webpack_require__(289) -var globSync = __webpack_require__(349) -var common = __webpack_require__(350) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(292) -var util = __webpack_require__(74) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored - -var once = __webpack_require__(294) - -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} - - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } - - return new Glob(pattern, options, cb) -} - -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync - -// old api surface -glob.glob = glob - -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } - - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin -} - -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - - var g = new Glob(pattern, options) - var set = g.minimatch.set - if (set.length > 1) - return true - - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } - - return false -} - -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length - - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) - - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } - - var self = this - var n = this.minimatch.set.length - this._processing = 0 - this.matches = new Array(n) - - this._emitQueue = [] - this._processQueue = [] - this.paused = false - - if (this.noprocess) - return this - - if (n === 0) - return done() - - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - - function done () { - --self._processing - if (self._processing <= 0) - self._finish() - } -} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - - common.finish(this) - this.emit('end', this.found) -} - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true - - var n = this.matches.length - if (n === 0) - return this._finish() - - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) - - function next () { - if (--n === 0) - self._finish() - } -} - -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - - var found = Object.keys(matchset) - var self = this - var n = found.length - - if (n === 0) - return cb() - - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - fs.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here - - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} - -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} - -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} - -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } -} - -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - - if (this.aborted) - return - - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } - - //console.error('PROCESS %d', this._processing, pattern) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} - -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} - -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() -} - -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (this.matches[index][e]) - return - - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - - var abs = this._makeAbs(e) - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } - - if (this.mark) - e = this._mark(e) - - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) - - this.emit('match', e) -} - -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) - - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - - if (lstatcb) - fs.lstat(abs, lstatcb) - - function lstatcb_ (er, lstat) { - if (er) - return cb() - - var isSym = lstat.isSymbolicLink() - self.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return - - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() - - if (Array.isArray(c)) - return cb(null, c) - } - - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) -} - -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} - -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return - - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - - this.cache[abs] = entries - return cb(null, entries) -} - -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - this.cache[this._makeAbs(f)] = 'FILE' - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } - - return cb() -} - -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} - - -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) - - var isSym = this.symlinks[abs] - var len = entries.length - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) - } - - cb() -} - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) - - if (needDir && c === 'FILE') - return cb() - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } - - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && !stat.isDirectory()) - return cb(null, false, stat) - - var c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c !== 'DIR') - return cb() - - return cb(null, c, stat) -} - - -/***/ }), -/* 349 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = globSync -globSync.GlobSync = GlobSync - -var fs = __webpack_require__(66) -var minimatch = __webpack_require__(283) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(348).Glob -var util = __webpack_require__(74) -var path = __webpack_require__(82) -var assert = __webpack_require__(108) -var isAbsolute = __webpack_require__(289) -var common = __webpack_require__(350) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored - -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - return new GlobSync(pattern, options).found -} - -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) - - setopts(this, pattern, options) - - if (this.noprocess) - return this - - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} - -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = fs.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} - - -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this.matches[index][e] = true - } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} - - -GlobSync.prototype._emitMatch = function (index, e) { - var abs = this._makeAbs(e) - if (this.mark) - e = this._mark(e) - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[this._makeAbs(e)] - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true - if (this.stat) - this._stat(e) -} - - -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) - - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - // lstat failed, doesn't exist - return null - } - - var isSym = lstat.isSymbolicLink() - this.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) - - return entries -} - -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries - - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null - - if (Array.isArray(c)) - return c - } - - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} - -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - - this.cache[abs] = entries - - // mark and cache dir-ness - return entries -} - -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - this.cache[this._makeAbs(f)] = 'FILE' - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} - -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) - - var len = entries.length - var isSym = this.symlinks[abs] - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} - -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this.matches[index][prefix] = true -} - -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - return false - } - - if (lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } - } - - this.statCache[abs] = stat - - var c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c !== 'DIR') - return false - - return c -} - -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} - -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - - -/***/ }), -/* 350 */ -/***/ (function(module, exports, __webpack_require__) { - -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored - -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} - -var path = __webpack_require__(82) -var minimatch = __webpack_require__(283) -var isAbsolute = __webpack_require__(289) -var Minimatch = minimatch.Minimatch - -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - -function alphasort (a, b) { - return a.localeCompare(b) -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || [] - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] - - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} - -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } - - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) - - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = options.cwd - self.changedCwd = path.resolve(options.cwd) !== cwd - } - - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - self.nomount = !!options.nomount - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } - } - - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) - - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - return !(/\/$/.test(e)) - }) - } - } - - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} - -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } - } - - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) - } - return abs -} - - -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - - -/***/ }), -/* 351 */ -/***/ (function(module, exports, __webpack_require__) { - -var path = __webpack_require__(82); -var fs = __webpack_require__(66); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; - - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - -var cc = __webpack_require__(353) -var join = __webpack_require__(82).join -var deepExtend = __webpack_require__(356) -var etc = '/etc' -var win = process.platform === "win32" -var home = win - ? process.env.USERPROFILE - : process.env.HOME - -module.exports = function (name, defaults, argv, parse) { - if('string' !== typeof name) - throw new Error('rc(name): name *must* be string') - if(!argv) - argv = __webpack_require__(357)(process.argv.slice(2)) - defaults = ( - 'string' === typeof defaults - ? cc.json(defaults) : defaults - ) || {} - - parse = parse || cc.parse - - var env = cc.env(name + '_') - - var configs = [defaults] - var configFiles = [] - function addConfigFile (file) { - if (configFiles.indexOf(file) >= 0) return - var fileConfig = cc.file(file) - if (fileConfig) { - configs.push(parse(fileConfig)) - configFiles.push(file) - } - } - - // which files do we look at? - if (!win) - [join(etc, name, 'config'), - join(etc, name + 'rc')].forEach(addConfigFile) - if (home) - [join(home, '.config', name, 'config'), - join(home, '.config', name), - join(home, '.' + name, 'config'), - join(home, '.' + name + 'rc')].forEach(addConfigFile) - addConfigFile(cc.find('.'+name+'rc')) - if (env.config) addConfigFile(env.config) - if (argv.config) addConfigFile(argv.config) - - return deepExtend.apply(null, configs.concat([ - env, - argv, - configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, - ])) -} - - -/***/ }), -/* 353 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var fs = __webpack_require__(66) -var ini = __webpack_require__(354) -var path = __webpack_require__(82) -var stripJsonComments = __webpack_require__(355) - -var parse = exports.parse = function (content) { - - //if it ends in .json or starts with { then it must be json. - //must be done this way, because ini accepts everything. - //can't just try and parse it and let it throw if it's not ini. - //everything is ini. even json with a syntax error. - - if(/^\s*{/.test(content)) - return JSON.parse(stripJsonComments(content)) - return ini.parse(content) - -} - -var file = exports.file = function () { - var args = [].slice.call(arguments).filter(function (arg) { return arg != null }) - - //path.join breaks if it's a not a string, so just skip this. - for(var i in args) - if('string' !== typeof args[i]) - return - - var file = path.join.apply(null, args) - var content - try { - return fs.readFileSync(file,'utf-8') - } catch (err) { - return - } -} - -var json = exports.json = function () { - var content = file.apply(null, arguments) - return content ? parse(content) : null -} - -var env = exports.env = function (prefix, env) { - env = env || process.env - var obj = {} - var l = prefix.length - for(var k in env) { - if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { - - var keypath = k.substring(l).split('__') - - // Trim empty strings from keypath array - var _emptyStringIndex - while ((_emptyStringIndex=keypath.indexOf('')) > -1) { - keypath.splice(_emptyStringIndex, 1) - } - - var cursor = obj - keypath.forEach(function _buildSubObj(_subkey,i){ - - // (check for _subkey first so we ignore empty strings) - // (check for cursor to avoid assignment to primitive objects) - if (!_subkey || typeof cursor !== 'object') - return - - // If this is the last key, just stuff the value in there - // Assigns actual value from env variable to final key - // (unless it's just an empty string- in that case use the last valid key) - if (i === keypath.length-1) - cursor[_subkey] = env[k] - - - // Build sub-object if nothing already exists at the keypath - if (cursor[_subkey] === undefined) - cursor[_subkey] = {} - - // Increment cursor used to track the object at the current depth - cursor = cursor[_subkey] - - }) - - } - - } - - return obj -} - -var find = exports.find = function () { - var rel = path.join.apply(null, [].slice.call(arguments)) - - function find(start, rel) { - var file = path.join(start, rel) - try { - fs.statSync(file) - return file - } catch (err) { - if(path.dirname(start) !== start) // root - return find(path.dirname(start), rel) - } - } - return find(process.cwd(), rel) -} - - - - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - -exports.parse = exports.decode = decode - -exports.stringify = exports.encode = encode - -exports.safe = safe -exports.unsafe = unsafe - -var eol = typeof process !== 'undefined' && - process.platform === 'win32' ? '\r\n' : '\n' - -function encode (obj, opt) { - var children = [] - var out = '' - - if (typeof opt === 'string') { - opt = { - section: opt, - whitespace: false - } - } else { - opt = opt || {} - opt.whitespace = opt.whitespace === true - } - - var separator = opt.whitespace ? ' = ' : '=' - - Object.keys(obj).forEach(function (k, _, __) { - var val = obj[k] - if (val && Array.isArray(val)) { - val.forEach(function (item) { - out += safe(k + '[]') + separator + safe(item) + '\n' - }) - } else if (val && typeof val === 'object') { - children.push(k) - } else { - out += safe(k) + separator + safe(val) + eol - } - }) - - if (opt.section && out.length) { - out = '[' + safe(opt.section) + ']' + eol + out - } - - children.forEach(function (k, _, __) { - var nk = dotSplit(k).join('\\.') - var section = (opt.section ? opt.section + '.' : '') + nk - var child = encode(obj[k], { - section: section, - whitespace: opt.whitespace - }) - if (out.length && child.length) { - out += eol - } - out += child - }) - - return out -} - -function dotSplit (str) { - return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') - .replace(/\\\./g, '\u0001') - .split(/\./).map(function (part) { - return part.replace(/\1/g, '\\.') - .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') - }) -} - -function decode (str) { - var out = {} - var p = out - var section = null - // section |key = value - var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i - var lines = str.split(/[\r\n]+/g) - - lines.forEach(function (line, _, __) { - if (!line || line.match(/^\s*[;#]/)) return - var match = line.match(re) - if (!match) return - if (match[1] !== undefined) { - section = unsafe(match[1]) - p = out[section] = out[section] || {} - return - } - var key = unsafe(match[2]) - var value = match[3] ? unsafe(match[4]) : true - switch (value) { - case 'true': - case 'false': - case 'null': value = JSON.parse(value) - } - - // Convert keys with '[]' suffix to an array - if (key.length > 2 && key.slice(-2) === '[]') { - key = key.substring(0, key.length - 2) - if (!p[key]) { - p[key] = [] - } else if (!Array.isArray(p[key])) { - p[key] = [p[key]] - } - } - - // safeguard against resetting a previously defined - // array by accidentally forgetting the brackets - if (Array.isArray(p[key])) { - p[key].push(value) - } else { - p[key] = value - } - }) - - // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} - // use a filter to return the keys that have to be deleted. - Object.keys(out).filter(function (k, _, __) { - if (!out[k] || - typeof out[k] !== 'object' || - Array.isArray(out[k])) { - return false - } - // see if the parent section is also an object. - // if so, add it to that, and mark this one for deletion - var parts = dotSplit(k) - var p = out - var l = parts.pop() - var nl = l.replace(/\\\./g, '.') - parts.forEach(function (part, _, __) { - if (!p[part] || typeof p[part] !== 'object') p[part] = {} - p = p[part] - }) - if (p === out && nl === l) { - return false - } - p[nl] = out[k] - return true - }).forEach(function (del, _, __) { - delete out[del] - }) - - return out -} - -function isQuoted (val) { - return (val.charAt(0) === '"' && val.slice(-1) === '"') || - (val.charAt(0) === "'" && val.slice(-1) === "'") -} - -function safe (val) { - return (typeof val !== 'string' || - val.match(/[=\r\n]/) || - val.match(/^\[/) || - (val.length > 1 && - isQuoted(val)) || - val !== val.trim()) - ? JSON.stringify(val) - : val.replace(/;/g, '\\;').replace(/#/g, '\\#') -} - -function unsafe (val, doUnesc) { - val = (val || '').trim() - if (isQuoted(val)) { - // remove the single quotes before calling JSON.parse - if (val.charAt(0) === "'") { - val = val.substr(1, val.length - 2) - } - try { val = JSON.parse(val) } catch (_) {} - } else { - // walk the val to find the first not-escaped ; character - var esc = false - var unesc = '' - for (var i = 0, l = val.length; i < l; i++) { - var c = val.charAt(i) - if (esc) { - if ('\\;#'.indexOf(c) !== -1) { - unesc += c - } else { - unesc += '\\' + c - } - esc = false - } else if (';#'.indexOf(c) !== -1) { - break - } else if (c === '\\') { - esc = true - } else { - unesc += c - } - } - if (esc) { - unesc += '\\' - } - return unesc.trim() - } - return val -} - - -/***/ }), -/* 355 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var singleComment = 1; -var multiComment = 2; - -function stripWithoutWhitespace() { - return ''; -} - -function stripWithWhitespace(str, start, end) { - return str.slice(start, end).replace(/\S/g, ' '); -} - -module.exports = function (str, opts) { - opts = opts || {}; - - var currentChar; - var nextChar; - var insideString = false; - var insideComment = false; - var offset = 0; - var ret = ''; - var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; - - for (var i = 0; i < str.length; i++) { - currentChar = str[i]; - nextChar = str[i + 1]; - - if (!insideComment && currentChar === '"') { - var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; - if (!escaped) { - insideString = !insideString; - } - } - - if (insideString) { - continue; - } - - if (!insideComment && currentChar + nextChar === '//') { - ret += str.slice(offset, i); - offset = i; - insideComment = singleComment; - i++; - } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { - i++; - insideComment = false; - ret += strip(str, offset, i); - offset = i; - continue; - } else if (insideComment === singleComment && currentChar === '\n') { - insideComment = false; - ret += strip(str, offset, i); - offset = i; - } else if (!insideComment && currentChar + nextChar === '/*') { - ret += str.slice(offset, i); - offset = i; - insideComment = multiComment; - i++; - continue; - } else if (insideComment === multiComment && currentChar + nextChar === '*/') { - i++; - insideComment = false; - ret += strip(str, offset, i + 1); - offset = i + 1; - continue; - } - } - - return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); -}; - - -/***/ }), -/* 356 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + ${i.join(` + `)} +augroup end`;try{let o=ke.default.join(process.env.TMPDIR,`coc.nvim-${process.pid}`);Dt.default.existsSync(o)||Dt.default.mkdirpSync(o);let s=ke.default.join(o,`coc-${process.pid}.vim`);Dt.default.writeFileSync(s,n,"utf8");let a=`source ${s}`;this.env.isCygwin&&Cl.isWindows&&(a=`execute "source" . substitute(system('cygpath ${s.replace(/\\/g,"/")}'), '\\n', '', 'g')`),this.nvim.command(a).logError()}catch(o){C.showMessage(`Can't create tmp file: ${o.message}`,"error")}}async onBufReadCmd(e,t){let i=this.schemeProviderMap.get(e);if(!i){C.showMessage(`Provider for ${e} not found`,"error");return}let n=new le.CancellationTokenSource,o=await Promise.resolve(i.provideTextDocumentContent($.parse(t),n.token)),s=await this.nvim.buffer;await s.setLines(o.split(/\r?\n/),{start:0,end:-1,strictIndexing:!1}),setTimeout(async()=>{await A.fire("BufCreate",[s.id])},30)}async attach(){if(this._attached)return;this._attached=!0;let[e,t,i]=await this.nvim.eval(`[map(getbufinfo({'bufloaded': 1}),'v:val["bufnr"]'),bufnr('%'),win_getid()]`);this.bufnr=t,await Promise.all(e.map(n=>this.onBufCreate(n))),this._initialized||(this._onDidWorkspaceInitialized.fire(void 0),this._initialized=!0),await A.fire("BufEnter",[t]),await A.fire("BufWinEnter",[t,i])}getChangedUris(e){let t=new Set,i=new Set;for(let n of e)if(le.TextDocumentEdit.is(n)){let{textDocument:o}=n,{uri:s,version:a}=o;if(t.add(s),a!=null&&a>0){let l=this.getDocument(s);if(!l)throw new Error(`${s} not loaded`);if(l.version!=a)throw new Error(`${s} changed before apply edit`)}}else if(le.CreateFile.is(n)||le.DeleteFile.is(n)){if(!Jm(n.uri))throw new Error(`change of scheme ${n.uri} not supported`);i.add(n.uri),t.add(n.uri)}else if(le.RenameFile.is(n)){if(!Jm(n.oldUri)||!Jm(n.newUri))throw new Error(`change of scheme ${n.oldUri} not supported`);let o=$.parse(n.newUri).fsPath;if(Dt.default.existsSync(o))throw new Error(`file "${o}" already exists for rename`);t.add(n.oldUri)}else throw new Error(`Invalid document change: ${JSON.stringify(n,null,2)}`);return Array.from(t)}createConfigurations(){let e=ke.default.normalize(process.env.COC_VIMCONFIG)||ke.default.join(Qi.default.homedir(),".vim"),t=ke.default.join(e,Gi);return new Q3(t,new ej(this))}attachChangedEvents(){if(this.isVim){let e=t=>{let i=this.getDocument(t);i&&i.attached&&i.fetchContent()};A.on("TextChangedI",e,null,this.disposables),A.on("TextChanged",e,null,this.disposables)}}async onBufCreate(e){let t=typeof e=="number"?this.nvim.createBuffer(e):e,i=t.id;if(this.creatingSources.has(i))return;let n=this.getDocument(i),o=new le.CancellationTokenSource;try{n&&this.onBufUnload(i,!0),n=new Zm(t,this._env,this.maxFileSize);let s=o.token;this.creatingSources.set(i,o),await n.init(this.nvim,s)||(n=null)}catch(s){op.error("Error on create buffer:",s),n=null}if(this.creatingSources.get(i)==o&&(o.dispose(),this.creatingSources.delete(i)),!(!n||!n.textDocument)){if(this.buffers.set(i,n),n.attached&&n.onDocumentDetach(s=>{let a=this.getDocument(s);a&&this.onBufUnload(a.bufnr)}),n.buftype==""&&n.schema=="file"&&(this.configurations.checkFolderConfiguration(n.uri),!this.getConfiguration("workspace").get("ignoredFiletypes",[]).includes(n.filetype))){let l=this.resolveRoot(n);l&&(this.addWorkspaceFolder(l),this.bufnr==t.id&&(this._root=l))}if(n.enabled){let s=Object.assign(n.textDocument,{bufnr:i});this._onDidOpenDocument.fire(s),n.onDocumentChange(a=>this._onDidChangeDocument.fire(a))}op.debug("buffer created",t.id)}}onBufEnter(e){this.bufnr=e;let t=this.getDocument(e);if(t){this.configurations.setFolderConfiguration(t.uri);let i=this.getWorkspaceFolder(t.uri);i&&(this._root=$.parse(i.uri).fsPath)}}async checkCurrentBuffer(e){this.bufnr=e,await this.checkBuffer(e)}onBufWritePost(e){let t=this.buffers.get(e);!t||this._onDidSaveDocument.fire(t.textDocument)}onBufUnload(e,t=!1){if(op.debug("buffer unload",e),!t){let n=this.creatingSources.get(e);n&&(n.cancel(),this.creatingSources.delete(e))}if(this.terminals.has(e)){let n=this.terminals.get(e);this._onDidCloseTerminal.fire(n),this.terminals.delete(e)}let i=this.buffers.get(e);if(i){let n=Object.assign(i.textDocument,{bufnr:e});this._onDidCloseDocument.fire(n),this.buffers.delete(e),i.detach()}}async onBufWritePre(e){let t=this.buffers.get(e);if(!t||!t.attached)return;await t.checkDocument();let i=!0,n=[],o={document:t.textDocument,reason:le.TextDocumentSaveReason.Manual,waitUntil:a=>{i?n.push(a):(op.error("Can't call waitUntil in async manner:",Error().stack),C.showMessage("waitUntil can't be used in async manner, check log for details","error"))}};this._onWillSaveDocument.fire(o),i=!1;let s=n.length;if(s){let l=await new Promise(u=>{let c=setTimeout(()=>{C.showMessage("Will save handler timeout after 0.5s","warning"),u(void 0)},500),f=0,p=!1;for(let d of n){let h=m=>{p||(p=!0,clearTimeout(c),u(m))};d.then(m=>{if(Array.isArray(m)&&m.length&&le.TextEdit.is(m[0]))return h(m);f=f+1,f==s&&h(void 0)},()=>{f=f+1,f==s&&h(void 0)})}});l&&await t.applyEdits(l)}}onDirChanged(e){e!=this._cwd&&(this._cwd=e)}onFileTypeChange(e,t){let i=this.getDocument(t);if(!i||i.convertFiletype(e)==i.filetype)return;let o=Object.assign(i.textDocument,{bufnr:t});this._onDidCloseDocument.fire(o),i.setFiletype(e),this._onDidOpenDocument.fire(Object.assign(i.textDocument,{bufnr:t}))}async checkBuffer(e){if(this._disposed||!e)return;!this.getDocument(e)&&!this.creatingSources.has(e)&&await this.onBufCreate(e)}resolveRoot(e){let t=[Kr.Buffer,Kr.LanguageServer,Kr.Global],i=$.parse(e.uri),n=ke.default.dirname(i.fsPath),{cwd:o}=this,s=this.getConfiguration("workspace"),a=s.get("bottomUpFiletypes",[]),l=s.get("workspaceFolderCheckCwd",!0);for(let u of t){let c=this.getRootPatterns(e,u);if(c&&c.length){let f=a.includes(e.filetype),p=Jf(n,c,o,f,l);if(p)return p}}return this.cwd!=Qi.default.homedir()&&Ye(this.cwd,n,!0)?this.cwd:null}getRootPatterns(e,t){let{uri:i}=e;return t==Kr.Buffer?e.getVar("root_patterns",[])||[]:t==Kr.LanguageServer?this.getServerRootPatterns(e.filetype):this.getConfiguration("coc.preferences",i).get("rootPatterns",[".git",".hg",".projections.json"]).slice()}async renameCurrent(){let{nvim:e}=this,t=await e.call("bufnr","%"),i=await e.call("getcwd"),n=this.getDocument(t);if(!n||n.buftype!=""||n.schema!="file"){e.errWriteLine("current buffer is not file.");return}let o=$.parse(n.uri).fsPath,s=await e.callAsync("coc#util#with_callback",["input",["New path: ",o,"file"]]);if(s=s?s.trim():null,s==o||!s)return;let a=await n.buffer.lines,l=Dt.default.existsSync(o);if(l){if(await e.eval("&modified")&&await e.command("noa w"),o.toLowerCase()!=s.toLowerCase()&&Dt.default.existsSync(s)){if(!await C.showPrompt(`${s} exists, overwrite?`))return;Dt.default.unlinkSync(s)}Dt.default.renameSync(o,s)}let u=Ye(i,s)?ke.default.relative(i,s):s,c=await e.call("winsaveview");e.pauseNotification(),o.toLowerCase()==s.toLowerCase()?(e.command(`keepalt ${t}bwipeout!`,!0),e.call("coc#util#open_file",["keepalt edit",u],!0)):(e.call("coc#util#open_file",["keepalt edit",u],!0),e.command(`${t}bwipeout!`,!0)),!l&&a.join(` +`)!=` +`&&(e.call("append",[0,a],!0),e.command("normal! Gdd",!0)),e.call("winrestview",[c],!0),await e.resumeNotification()}get folderPaths(){return this.workspaceFolders.map(e=>$.parse(e.uri).fsPath)}get floatSupported(){let{env:e}=this;return e.floating||e.textprop}removeWorkspaceFolder(e){let t=this._workspaceFolders.findIndex(i=>$.parse(i.uri).fsPath==e);if(t!=-1){let i=this._workspaceFolders[t];this._workspaceFolders.splice(t,1),this._onDidChangeWorkspaceFolders.fire({removed:[i],added:[]})}}renameWorkspaceFolder(e,t){let i=this._workspaceFolders.findIndex(s=>$.parse(s.uri).fsPath==e);if(i==-1)return;let n=this._workspaceFolders[i],o={uri:$.file(t).toString(),name:ke.default.dirname(t)};this._workspaceFolders.splice(i,1),this._workspaceFolders.push(o),this._onDidChangeWorkspaceFolders.fire({removed:[n],added:[o]})}addRootPattern(e,t){let i=this.rootPatterns.get(e)||[];for(let n of t)i.includes(n)||i.push(n);this.rootPatterns.set(e,i)}get insertMode(){return this._insertMode}async detach(){if(!!this._attached){this._attached=!1,Xs.dispose();for(let e of this.buffers.keys())await A.fire("BufUnload",[e])}}dispose(){this._disposed=!0;for(let e of this.documents)e.detach();z(this.disposables),ta.dispose(),this.configurations.dispose(),this.buffers.clear()}addWorkspaceFolder(e){if(e==Qi.default.homedir())return;let{_workspaceFolders:t}=this,i=$.file(e).toString(),n={uri:i,name:ke.default.basename(e)};return t.findIndex(o=>o.uri==i)==-1&&(t.push(n),this._initialized&&this._onDidChangeWorkspaceFolders.fire({added:[n],removed:[]})),n}getServerRootPatterns(e){let t=this.getConfiguration().get("languageserver",{}),i=[];for(let n of Object.keys(t)){let o=t[n],{filetypes:s,rootPatterns:a}=o;s&&a&&s.includes(e)&&i.push(...a)}return i=i.concat(this.rootPatterns.get(e)||[]),i.length?eg(i):null}},b=new Uj;var Kl=j()("window"),zj=class{constructor(){this.mutex=new ar}get nvim(){return b.nvim}dispose(){var e;(e=this.statusLine)==null||e.dispose()}showMessage(e,t="more"){if(this.mutex.busy||!this.nvim)return;let{messageLevel:i}=this,n=process.env.VIM_NODE_RPC=="1"?"callTimer":"call";global.hasOwnProperty("__TEST__")&&Kl.info(e);let o="Error",s=gn.Error;switch(t){case"more":s=gn.More,o="MoreMsg";break;case"warning":s=gn.Warning,o="WarningMsg";break}s>=i&&this.nvim[n]("coc#util#echo_messages",[o,("[coc.nvim] "+e).split(` +`)],!0)}async runTerminalCommand(e,t,i=!1){return t=t||b.cwd,await this.nvim.callAsync("coc#util#run_terminal",{cmd:e,cwd:t,keepfocus:i?1:0})}async openTerminal(e,t={}){return await this.nvim.call("coc#util#open_terminal",{cmd:e,...t})}async showQuickpick(e,t="Choose by number"){let i=await this.mutex.acquire();try{let n=t+":";e=e.map((a,l)=>`${l+1}. ${a}`);let o=await this.nvim.callAsync("coc#util#quickpick",[n,e.map(a=>a.trim())]);i();let s=parseInt(o,10);return isNaN(s)||s<=0||s>e.length?-1:s-1}catch(n){return i(),-1}}async showMenuPicker(e,t,i){if(b.env.dialog){let n=await this.mutex.acquire();if(i&&i.isCancellationRequested){n();return}try{let o=new GB(this.nvim,{items:e.map(l=>l.trim()),title:t},i),s=new Promise(l=>{o.onDidClose(u=>{l(u)})});await o.show(this.dialogPreference);let a=await s;return n(),a}catch(o){Kl.error("Error on showMenuPicker:",o),n()}}return await this.showQuickpick(e)}async openLocalConfig(){let{root:e}=b;if(e==Wj.default.homedir()){this.showMessage("Can't create local config in home directory","warning");return}let t=D0.default.join(e,".vim");if(!x0.default.existsSync(t)){if(!await this.showPrompt(`Would you like to create folder'${e}/.vim'?`))return;x0.default.mkdirSync(t)}await b.jumpTo($.file(D0.default.join(t,Gi)).toString())}async showPrompt(e){let t=await this.mutex.acquire();try{let i=await this.nvim.callAsync("coc#float#prompt_confirm",[e]);return t(),i==1}catch(i){return t(),!1}}async showDialog(e){if(!this.checkDialog())return null;let t=new HB(this.nvim,e);return await t.show(this.dialogPreference),t}async requestInput(e,t){let{nvim:i}=this,n=b.getConfiguration("coc.preferences");if(b.env.dialog&&n.get("promptInput",!0)&&!Hn){let o=await this.mutex.acquire(),s=this.dialogPreference;try{let a={};s.floatHighlight&&(a.highlight=s.floatHighlight),s.floatBorderHighlight&&(a.borderhighlight=s.floatBorderHighlight);let l=await i.call("coc#float#create_prompt_win",[e,t||"",a]),[u,c]=l,f=await new Promise(p=>{let d=[];A.on("BufWinLeave",h=>{h==u&&(z(d),p(null))},null,d),A.on("PromptInsert",async h=>{z(d),await i.call("coc#float#close",[c]),h?p(h):(this.showMessage("Empty word, canceled","warning"),p(null))},null,d)});return o(),f}catch(a){Kl.error("Error on requestInput:",a),o()}}else{let o=await b.callAsync("input",[e+": ",t||""]);return i.command("normal! :",!0),o||(this.showMessage("Empty word, canceled","warning"),null)}}createStatusBarItem(e=0,t={}){if(!b.env){let i=()=>{};return{text:"",show:i,dispose:i,hide:i,priority:0,isProgress:!1}}return this.statusLine||(this.statusLine=new r3(this.nvim)),this.statusLine.createStatusBarItem(e,t.progress||!1)}createOutputChannel(e){return Xs.create(e,this.nvim)}showOutputChannel(e,t){Xs.show(e,t)}async echoLines(e,t=!1){let{nvim:i}=this,n=b.env.cmdheight;e.length>n&&t&&(e=e.slice(0,n));let o=b.env.columns-12;if(e=e.map(s=>(s=s.replace(/\n/g," "),t&&(s=s.slice(0,o)),s)),t&&e.length==n){let s=e[e.length-1];e[n-1]=`${s.length==o?s.slice(0,-4):s} ...`}await i.call("coc#util#echo_lines",[e])}async getCursorPosition(){let[e,t]=await this.nvim.eval("[line('.')-1, strpart(getline('.'), 0, col('.') - 1)]");return Hj.Position.create(e,t.length)}async moveTo(e){await this.nvim.call("coc#util#jumpTo",[e.line,e.character]),b.env.isVim&&this.nvim.command("redraw",!0)}async getOffset(){return await this.nvim.call("coc#util#get_offset")}async getCursorScreenPosition(){let[e,t]=await this.nvim.call("coc#util#cursor_pos");return{row:e,col:t}}async showPickerDialog(e,t,i){if(!this.checkDialog())return;let n=await this.mutex.acquire();if(i&&i.isCancellationRequested){n();return}try{let o=typeof e[0]=="string",s=new YB(this.nvim,{title:t,items:o?e.map(c=>({label:c})):e},i),a=new Promise(c=>{s.onDidClose(f=>{c(f)})});await s.show(this.dialogPreference);let l=await a,u=l==null?void 0:e.filter((c,f)=>l.includes(f));return n(),u}catch(o){Kl.error("Error on showPickerDialog:",o),n()}}async showInformationMessage(e,...t){if(!this.enableMessageDialog)return await this.showConfirm(e,t,"Info");let i=typeof t[0]=="string"?t:t.map(o=>o.title),n=await this.createNotification("CocInfoFloat",e,i);return n==-1?void 0:t[n]}async showWarningMessage(e,...t){if(!this.enableMessageDialog)return await this.showConfirm(e,t,"Warning");let i=typeof t[0]=="string"?t:t.map(o=>o.title),n=await this.createNotification("CocWarningFloat",e,i);return n==-1?void 0:t[n]}async showErrorMessage(e,...t){if(!this.enableMessageDialog)return await this.showConfirm(e,t,"Error");let i=typeof t[0]=="string"?t:t.map(o=>o.title),n=await this.createNotification("CocErrorFloat",e,i);return n==-1?void 0:t[n]}async showNotification(e){return this.checkDialog()?await new qf(this.nvim,e).show(this.notificationPreference):!1}async showConfirm(e,t,i){if(!t||t.length==0){let a=i=="Info"?"more":i=="Error"?"error":"warning";this.showMessage(e,a);return}let o=(typeof t[0]=="string"?t.slice():t.map(a=>a.title)).map((a,l)=>`${l+1}${a}`),s=await this.nvim.callAsync("coc#util#with_callback",["confirm",[e,o.join(` +`),0,i]]);return t[s-1]}async withProgress(e,t){return this.checkDialog()?await new ZB(this.nvim,{task:t,title:e.title,cancellable:e.cancellable}).show(this.notificationPreference):void 0}createNotification(e,t,i){return new Promise(n=>{let o={content:t,borderhighlight:e,close:!0,buttons:i.map((a,l)=>({text:a,index:l})),callback:a=>{n(a)}};new qf(this.nvim,o).show(this.notificationPreference).then(a=>{a||(Kl.error("Unable to open notification window"),n(-1)),i.length||n(-1)},a=>{Kl.error("Unable to open notification window",a),n(-1)})})}get dialogPreference(){let e=b.getConfiguration("dialog");return{maxWidth:e.get("maxWidth"),maxHeight:e.get("maxHeight"),floatHighlight:e.get("floatHighlight"),floatBorderHighlight:e.get("floatBorderHighlight"),pickerButtons:e.get("pickerButtons"),pickerButtonShortcut:e.get("pickerButtonShortcut"),confirmKey:e.get("confirmKey")}}get notificationPreference(){let e=b.getConfiguration("notification");return{top:e.get("marginTop"),right:e.get("marginRight"),maxWidth:e.get("maxWidth"),maxHeight:e.get("maxHeight"),highlight:e.get("highlightGroup"),minProgressWidth:e.get("minProgressWidth")}}checkDialog(){return b.env.dialog?!0:(this.showMessage("Dialog requires vim >= 8.2.0750 or neovim >= 0.4.0, please upgrade your vim","warning"),!1)}get enableMessageDialog(){return b.env.dialog?b.getConfiguration("coc.preferences").get("enableMessageDialog",!1):!1}get messageLevel(){switch(b.getConfiguration("coc.preferences").get("messageLevel","more")){case"error":return gn.Error;case"warning":return gn.Warning;default:return gn.More}}},C=new zj;var Vj=S(Gr()),Qr=S(W());var Lt=S(W());function sp(r){switch(r){case Lt.DiagnosticSeverity.Error:return"Error";case Lt.DiagnosticSeverity.Warning:return"Warning";case Lt.DiagnosticSeverity.Information:return"Information";case Lt.DiagnosticSeverity.Hint:return"Hint";default:return"Error"}}function Gj(r){switch(r){case Lt.DiagnosticSeverity.Error:return"E";case Lt.DiagnosticSeverity.Warning:return"W";case Lt.DiagnosticSeverity.Information:return"I";case Lt.DiagnosticSeverity.Hint:return"I";default:return"Error"}}function S0(r){switch(r){case"hint":return Lt.DiagnosticSeverity.Hint;case"information":return Lt.DiagnosticSeverity.Information;case"warning":return Lt.DiagnosticSeverity.Warning;case"error":return Lt.DiagnosticSeverity.Error;default:return Lt.DiagnosticSeverity.Hint}}function fg(r){switch(r){case Lt.DiagnosticSeverity.Error:return"CocError";case Lt.DiagnosticSeverity.Warning:return"CocWarning";case Lt.DiagnosticSeverity.Information:return"CocInfo";case Lt.DiagnosticSeverity.Hint:return"CocHint";default:return"CocError"}}function pg(r,e){let{start:t}=e.range,i=e.source||"coc.nvim",n=e.message.split(` +`)[0],o=sp(e.severity).slice(0,1).toUpperCase();return{bufnr:r,lnum:t.line+1,col:t.character+1,text:`[${i}${e.code?" "+e.code:""}] ${n} [${o}]`,type:o}}var Xde=j()("diagnostic-buffer"),Kj="CocDiagnostic",Zde=Symbol("CocError"),Qde=Symbol("CocWarning"),ehe=Symbol("CocInformation"),the=Symbol("CocHint"),E0=class{constructor(e,t,i,n,o){this.nvim=e;this.bufnr=t;this.uri=i;this.config=n;this.onRefresh=o;this.diagnostics=[];this._disposed=!1;this.refresh=Vj.default(s=>{this._refresh(s).logError()},300)}get displayByAle(){return this.config.displayByAle}onChange(){this.refresh.clear()}forceRefresh(e){this.refresh.clear(),this._refresh(e).logError()}refreshAle(e){let t=Jj(this.diagnostics);this.diagnostics=e;let i=new Map;e.forEach(n=>{let o=i.get(n.collection)||[];o.push(n),i.set(n.collection,o)});for(let n of t)i.has(n)||i.set(n,[]);this.nvim.pauseNotification();for(let[n,o]of i.entries()){let s=o.map(l=>{let u=l.range||Qr.Range.create(0,0,1,0);return{text:l.message,code:l.code,lnum:u.start.line+1,col:u.start.character+1,end_lnum:u.end.line+1,end_col:u.end.character,type:Gj(l.severity)}}),a=global.hasOwnProperty("__TEST__")?"MockAleResults":"ale#other_source#ShowResults";this.nvim.call(a,[this.bufnr,n,s],!0)}this.nvim.resumeNotification().then(n=>{Array.isArray(n)&&n[1]!=null&&Xde.error("Error on displayByAle:",n[1][2])}).logError()}async _refresh(e){if(Ne(this.diagnostics,e))return;let{refreshOnInsertMode:t}=this.config,{nvim:i}=this,n=await i.eval(`[coc#util#check_refresh(${this.bufnr}),mode(),line("."),getloclist(bufwinid(${this.bufnr}),{'title':1})]`);if(n[0]==0||this._disposed)return;let o=n[1];if(!(!t&&o.startsWith("i")&&e.length)){if(this.displayByAle)this.refreshAle(e);else{this.diagnostics=e;let s=n[2];i.pauseNotification(),this.setDiagnosticInfo(e),this.addSigns(e),this.addHighlight(e),this.updateLocationList(n[3],e),this.showVirtualText(e,s),this.nvim.command("redraw",!0);let a=await this.nvim.resumeNotification();if(Array.isArray(a)&&a[1])throw new Error(a[1])}this.onRefresh(e)}}updateLocationList(e,t){if(!this.config.locationlistUpdate||!e||e.title!=="Diagnostics of coc")return;let i=[];for(let n of t){let o=pg(this.bufnr,n);i.push(o)}this.nvim.call("setloclist",[0,[],"r",{title:"Diagnostics of coc",items:i}],!0)}addSigns(e){if(!this.config.enableSign)return;this.clearSigns();let{nvim:t,bufnr:i}=this,n=new Map;for(let o of e){let{range:s,severity:a}=o,l=s.start.line,u=fg(a),c=n.get(l)||[],f=rhe(a);c.includes(f)||(c.push(f),n.set(l,c),t.call("sign_place",[0,Kj,u,i,{lnum:l+1,priority:14-(a||0)}],!0))}}clearSigns(){let{nvim:e,bufnr:t}=this;e.call("sign_unplace",[Kj,{buffer:t}],!0)}setDiagnosticInfo(e){let t=[0,0,0,0],i={error:0,warning:0,information:0,hint:0,lnums:t};for(let n of e)switch(n.severity){case Qr.DiagnosticSeverity.Warning:i.warning=i.warning+1,t[1]=t[1]||n.range.start.line+1;break;case Qr.DiagnosticSeverity.Information:i.information=i.information+1,t[2]=t[2]||n.range.start.line+1;break;case Qr.DiagnosticSeverity.Hint:i.hint=i.hint+1,t[3]=t[3]||n.range.start.line+1;break;default:t[0]=t[0]||n.range.start.line+1,i.error=i.error+1}this.nvim.call("coc#util#set_buf_var",[this.bufnr,"coc_diagnostic_info",i],!0),this.nvim.call("coc#util#do_autocmd",["CocDiagnosticChange"],!0)}showVirtualText(e,t){let{buffer:i,config:n}=this;if(!n.virtualText)return;let o=this.config.virtualTextSrcId,s=this.config.virtualTextPrefix;this.config.virtualTextCurrentLineOnly&&(e=e.filter(a=>{let{start:l,end:u}=a.range;return l.line<=t-1&&u.line>=t-1})),i.clearNamespace(o);for(let a of[...e].reverse()){let{line:l}=a.range.start,u=fg(a.severity)+"VirtualText",c=a.message.split(/\n/).map(f=>f.trim()).filter(f=>f.length>0).slice(0,this.config.virtualTextLines).join(this.config.virtualTextLineSeparator);i.setVirtualText(o,l,[[s+c,u]],{}).logError()}}addHighlight(e){if(this.clearHighlight(),e.length==0)return;let t=new Map;for(let i of e){let{range:n,severity:o}=i,s=t.get(o)||[];s.push(n),t.set(o,s)}for(let i of[Qr.DiagnosticSeverity.Hint,Qr.DiagnosticSeverity.Information,Qr.DiagnosticSeverity.Warning,Qr.DiagnosticSeverity.Error]){let n=t.get(i)||[],o=fg(i)+"Highlight";this.buffer.highlightRanges("diagnostic",o,n)}}clearHighlight(){this.buffer.clearNamespace("diagnostic")}get buffer(){return this.nvim.createBuffer(this.bufnr)}clear(){this.refresh.clear();let{nvim:e}=this;if(this.displayByAle){let t=Jj(this.diagnostics);if(this.diagnostics=[],t.size>0)for(let i of t){let n=global.hasOwnProperty("__TEST__")?"MockAleResults":"ale#other_source#ShowResults";this.nvim.call(n,[this.bufnr,i,[]],!0)}}else this.diagnostics=[],e.pauseNotification(),this.clearHighlight(),this.config.enableSign&&this.clearSigns(),this.config.virtualText&&this.buffer.clearNamespace(this.config.virtualTextSrcId),this.setDiagnosticInfo([]),e.resumeNotification(!1,!0)}getDiagnosticsAt(e,t){let i=this.diagnostics.slice();return t?i=i.filter(n=>qB(e.line,n.range)):i=i.filter(n=>Wt(e,n.range)==0),i.sort((n,o)=>n.severity-o.severity),i}dispose(){this._disposed=!0,this.clear()}};function Jj(r){let e=new Set;return r.forEach(t=>{e.add(t.collection)}),e}function rhe(r){return r==Qr.DiagnosticSeverity.Error?Zde:r==Qr.DiagnosticSeverity.Warning?Qde:r==Qr.DiagnosticSeverity.Information?ehe:the}var Jl=S(W());var lAe=j()("diagnostic-collection"),C0=class{constructor(e){this.diagnosticsMap=new Map;this._onDispose=new Jl.Emitter;this._onDidDiagnosticsChange=new Jl.Emitter;this._onDidDiagnosticsClear=new Jl.Emitter;this.onDispose=this._onDispose.event;this.onDidDiagnosticsChange=this._onDidDiagnosticsChange.event;this.onDidDiagnosticsClear=this._onDidDiagnosticsClear.event;this.name=e}set(e,t){let i=new Map;if(Array.isArray(e))for(let n of e){let[o,s]=n,a=b.getDocument(o);o=a?a.uri:o,s==null?s=[]:s=(i.get(o)||[]).concat(s),i.set(o,s)}else{let n=b.getDocument(e),o=n?n.uri:e;i.set(o,t||[])}for(let n of i){let[o,s]=n;o=$.parse(o).toString(),s.forEach(a=>{a.range=a.range||Jl.Range.create(0,0,1,0),a.message=a.message||"Empty error message",Gn(a.range)&&(a.range.end={line:a.range.end.line,character:a.range.end.character+1});let{start:l,end:u}=a.range;if(u.character==0&&u.line-l.line==1&&l.character>0){let c=b.getDocument(o);if(c){let f=c.getline(l.line);l.character==f.length&&(a.range.start.character=l.character-1)}}a.source=a.source||this.name}),this.diagnosticsMap.set(o,s),this._onDidDiagnosticsChange.fire(o)}}delete(e){this.diagnosticsMap.delete(e)}clear(){let e=Array.from(this.diagnosticsMap.keys());this.diagnosticsMap.clear(),this._onDidDiagnosticsClear.fire(e)}forEach(e,t){for(let i of this.diagnosticsMap.keys()){let n=this.diagnosticsMap.get(i);e.call(t,i,n,this)}}get(e){let t=this.diagnosticsMap.get(e);return t==null?[]:t}has(e){return this.diagnosticsMap.has(e)}dispose(){this.clear(),this._onDispose.fire(void 0),this._onDispose.dispose(),this._onDidDiagnosticsClear.dispose(),this._onDidDiagnosticsChange.dispose()}},Yj=C0;var DAe=j()("diagnostic-manager"),Qj=class{constructor(){this.enabled=!0;this._onDidRefresh=new dt.Emitter;this.onDidRefresh=this._onDidRefresh.event;this.lastMessage="";this.collections=[];this.disposables=[]}init(){this.setConfiguration(),b.onDidChangeConfiguration(t=>{this.setConfiguration(t)},null,this.disposables),this.floatFactory=new mn(this.nvim),this.buffers=b.registerBufferSync(t=>{if(t.buftype!=="")return;let i=new E0(this.nvim,t.bufnr,t.uri,this.config,o=>{this._onDidRefresh.fire({diagnostics:o,uri:i.uri,bufnr:i.bufnr}),!["never","jump"].includes(this.config.enableMessage)&&this.echoMessage(!0).logError()}),n=this.getDiagnostics(t.uri);return this.enabled&&i.forceRefresh(n),i}),A.on("CursorMoved",t=>{this.config.enableMessage=="always"&&(this.timer&&clearTimeout(this.timer),t!=this.floatFactory.bufnr&&(this.timer=setTimeout(async()=>{await this.echoMessage(!0)},this.config.messageDelay)))},null,this.disposables);let e=Xj.default((t,i)=>{if(!this.config.virtualText||!this.config.virtualTextCurrentLineOnly)return;let n=this.buffers.getItem(t);if(n){let o=this.getDiagnostics(n.uri);n.showVirtualText(o,i[0])}},100);A.on("CursorMoved",e,null,this.disposables),this.disposables.push(dt.Disposable.create(()=>{e.clear()})),A.on("InsertLeave",async t=>{this.config.refreshOnInsertMode||this.refreshBuffer(t)},null,this.disposables),A.on("BufEnter",async()=>{this.timer&&clearTimeout(this.timer)},null,this.disposables),this.setConfigurationErrors(!0),b.configurations.onError(()=>{this.setConfigurationErrors()},null,this.disposables)}defineSigns(){let{nvim:e}=this,{enableHighlightLineNumber:t,enableSign:i}=this.config;if(!!i){e.pauseNotification();for(let n of["Error","Warning","Info","Hint"]){let o=this.config[n.toLowerCase()+"Sign"],s=`sign define Coc${n} linehl=Coc${n}Line`;o&&(s+=` texthl=Coc${n}Sign text=${o}`),t&&(s+=` numhl=Coc${n}Sign`),e.command(s,!0)}e.resumeNotification(!1,!0)}}async setLocationlist(e){let t=this.buffers.getItem(e),i=t?this.getDiagnostics(t.uri):[],n=[];for(let a of i){let l=pg(e,a);n.push(l)}let o=await this.nvim.call("getloclist",[0,{title:1}]),s=o.title&&o.title.indexOf("Diagnostics of coc")!=-1?"r":" ";await this.nvim.call("setloclist",[0,[],s,{title:"Diagnostics of coc",items:n}])}setConfigurationErrors(e){let i=this.collections.find(o=>o.name=="config");i?i.clear():i=this.create("config");let{errorItems:n}=b.configurations;if(n&&n.length){e&&C.showMessage("settings file parse error, run ':CocList diagnostics'","error");let o=new Map;for(let s of n){let{uri:a}=s.location,l=o.get(a)||[];l.push(dt.Diagnostic.create(s.location.range,s.message,dt.DiagnosticSeverity.Error)),o.set(a,l)}i.set(Array.from(o))}}create(e){let t=this.getCollectionByName(e);return t||(t=new Yj(e),this.collections.push(t),t.onDidDiagnosticsChange(i=>{this.refreshBuffer(i)}),t.onDidDiagnosticsClear(i=>{for(let n of i)this.refreshBuffer(n,!0)}),t.onDispose(()=>{let i=this.collections.findIndex(n=>n==t);i!==-1&&this.collections.splice(i,1)}),t)}getSortedRanges(e,t){let i=this.getCollections(e),n=[],o=t?S0(t):0;for(let s of i){let a=s.get(e);o&&(a=a.filter(u=>u.severity==o));let l=a.map(u=>u.range);n.push(...l)}return n.sort((s,a)=>s.start.line!=a.start.line?s.start.line-a.start.line:s.start.character-a.start.character),n}getDiagnostics(e){let t=this.getCollections(e),{level:i,showUnused:n,showDeprecated:o}=this.config,s=[];for(let a of t){let l=a.get(e);!l||(l=l.filter(u=>{var c,f;return!(i&&ii||!n&&((c=u.tags)==null?void 0:c.includes(dt.DiagnosticTag.Unnecessary))||!o&&((f=u.tags)==null?void 0:f.includes(dt.DiagnosticTag.Deprecated)))}),l.forEach(u=>{s.push(Object.assign({collection:a.name},u))}))}return s.sort((a,l)=>{if(a.severity==l.severity){let u=Me(a.range.start,l.range.start);return u!=0?u:a.source==l.source?a.message>l.message?1:-1:a.source>l.source?1:-1}return a.severity-l.severity}),s}getDiagnosticsInRange(e,t){let i=this.getCollections(e.uri),n=[];for(let o of i){let s=o.get(e.uri);if(!!s)for(let a of s)ql(a.range,t)&&n.push(a)}return n}async preview(){let[e,t]=await this.nvim.eval('[bufnr("%"),coc#util#cursor()]'),{nvim:i}=this,n=this.getDiagnosticsAt(e,t);if(n.length==0){i.command("pclose",!0),C.showMessage("Empty diagnostics","warning");return}let o=[];for(let s of n){let{source:a,code:l,severity:u,message:c}=s,f=sp(u)[0];o.push(`[${a}${l?" "+l:""}] [${f}]`),o.push(...c.split(/\r?\n/)),o.push("")}i.call("coc#util#preview_info",[o,"txt"],!0)}async jumpPrevious(e){let t=await this.nvim.buffer,i=b.getDocument(t.id);if(!i)return;let n=await C.getCursorPosition(),o=this.getSortedRanges(i.uri,e);if(o.length==0){C.showMessage("Empty diagnostics","warning");return}let s;for(let a=o.length-1;a>=0;a--){let l=o[a].end;if(Me(l,n)<0){s=o[a].start;break}else a==0&&await this.nvim.getOption("wrapscan")&&(s=o[o.length-1].start)}if(s){if(await C.moveTo(s),this.config.enableMessage=="never")return;await this.echoMessage(!1)}}async jumpNext(e){let t=await this.nvim.buffer,i=b.getDocument(t.id),n=await C.getCursorPosition(),o=this.getSortedRanges(i.uri,e);if(o.length==0){C.showMessage("Empty diagnostics","warning");return}let s;for(let a=0;a<=o.length-1;a++){let l=o[a].start;if(Me(l,n)>0){s=o[a].start;break}else a==o.length-1&&await this.nvim.getOption("wrapscan")&&(s=o[0].start)}if(s){if(await C.moveTo(s),this.config.enableMessage=="never")return;await this.echoMessage(!1)}}getDiagnosticList(){let e=[],{level:t,showUnused:i,showDeprecated:n}=this.config;for(let o of this.collections)o.forEach((s,a)=>{var u,c;let l=$.parse(s).fsPath;for(let f of a){if(f.severity&&f.severity>t||!i&&((u=f.tags)==null?void 0:u.includes(dt.DiagnosticTag.Unnecessary))||!n&&((c=f.tags)==null?void 0:c.includes(dt.DiagnosticTag.Deprecated)))continue;let{start:p}=f.range,d={file:l,lnum:p.line+1,col:p.character+1,code:f.code,source:f.source||o.name,message:f.message,severity:sp(f.severity),level:f.severity||0,location:dt.Location.create(s,f.range)};e.push(d)}});return e.sort((o,s)=>o.level!==s.level?o.level-s.level:o.file!==s.file?o.file>s.file?1:-1:o.lnum!=s.lnum?o.lnum-s.lnum:o.col-s.col),e}getDiagnosticsAt(e,t){let i=this.buffers.getItem(e);if(!i)return[];let n=dt.Position.create(t[0],t[1]);return i.getDiagnosticsAt(n,this.config.checkCurrentLine)}async getCurrentDiagnostics(){let[e,t]=await this.nvim.eval('[bufnr("%"),coc#util#cursor()]');return this.getDiagnosticsAt(e,t)}async echoMessage(e=!1){let t=this.config;if(!this.enabled||t.displayByAle)return;this.timer&&clearTimeout(this.timer);let i=t.messageTarget=="float",[n,o,s,a]=await this.nvim.eval('[bufnr("%"),coc#util#cursor(),&filetype,mode()]');if(a!="n")return;let l=this.getDiagnosticsAt(n,o);if(l.length==0){if(i)this.floatFactory.close();else{let f=await this.nvim.call("coc#util#echo_line");this.lastMessage&&f.startsWith(this.lastMessage)&&this.nvim.command('echo ""',!0)}return}if(e&&b.insertMode)return;let u=[],c="";if(Object.keys(t.filetypeMap).length>0){let f=t.filetypeMap.default||"";c=t.filetypeMap[s]||(f=="bufferType"?s:f)}if(l.forEach(f=>{let{source:p,code:d,severity:h,message:m}=f,y=sp(h)[0],v=d?" "+d:"",x=t.format.replace("%source",p).replace("%code",v).replace("%severity",y).replace("%message",m),w="Error";if(c==="")switch(h){case dt.DiagnosticSeverity.Hint:w="Hint";break;case dt.DiagnosticSeverity.Warning:w="Warning";break;case dt.DiagnosticSeverity.Information:w="Info";break}else w=c;u.push({filetype:w,content:x})}),i){let{maxWindowHeight:f,maxWindowWidth:p}=this.config;await this.floatFactory.show(u,{maxWidth:p,maxHeight:f,modes:["n"]})}else{let f=u.map(p=>p.content).join(` +`).split(/\r?\n/);f.length&&(await this.nvim.command('echo ""'),this.lastMessage=f[0].slice(0,30),await C.echoLines(f,e))}}async jumpRelated(){let e=await this.getCurrentDiagnostics();if(!e)return;let t=e.find(n=>n.relatedInformation!=null);if(!t)return;let i=t.relatedInformation.map(n=>n.location);i.length==1?await b.jumpTo(i[0].uri,i[0].range.start):i.length>1&&await b.showLocations(i)}reset(){this.timer&&clearTimeout(this.timer),this.buffers.reset();for(let e of this.collections)e.dispose();this.collections=[]}dispose(){var e;this.buffers.dispose(),this.timer&&clearTimeout(this.timer);for(let t of this.collections)t.dispose();(e=this.floatFactory)==null||e.close(),this.collections=[],z(this.disposables)}get nvim(){return b.nvim}setConfiguration(e){if(e&&!e.affectsConfiguration("diagnostic"))return;let t=b.getConfiguration("diagnostic"),i=t.get("messageTarget","float");i=="float"&&!b.env.floating&&!b.env.textprop&&(i="echo");let n=t.get("enableHighlightLineNumber",!0);(!b.isNvim||Zj.default.lt(b.env.version,"v0.3.2"))&&(n=!1),this.config={messageTarget:i,enableHighlightLineNumber:n,virtualTextSrcId:b.createNameSpace("diagnostic-virtualText"),checkCurrentLine:t.get("checkCurrentLine",!1),enableSign:b.env.sign&&t.get("enableSign",!0),locationlistUpdate:t.get("locationlistUpdate",!0),maxWindowHeight:t.get("maxWindowHeight",10),maxWindowWidth:t.get("maxWindowWidth",80),enableMessage:t.get("enableMessage","always"),messageDelay:t.get("messageDelay",200),virtualText:t.get("virtualText",!1)&&this.nvim.hasFunction("nvim_buf_set_virtual_text"),virtualTextCurrentLineOnly:t.get("virtualTextCurrentLineOnly",!0),virtualTextPrefix:t.get("virtualTextPrefix"," "),virtualTextLineSeparator:t.get("virtualTextLineSeparator"," \\ "),virtualTextLines:t.get("virtualTextLines",3),displayByAle:t.get("displayByAle",!1),level:S0(t.get("level","hint")),signPriority:t.get("signPriority",10),errorSign:t.get("errorSign",">>"),warningSign:t.get("warningSign",">>"),infoSign:t.get("infoSign",">>"),hintSign:t.get("hintSign",">>"),refreshOnInsertMode:t.get("refreshOnInsertMode",!1),filetypeMap:t.get("filetypeMap",{}),showUnused:t.get("showUnused",!0),showDeprecated:t.get("showDeprecated",!0),format:t.get("format","[%source%code] [%severity] %message")},this.enabled=t.get("enable",!0),this.defineSigns()}getCollectionByName(e){return this.collections.find(t=>t.name==e)}getCollections(e){return this.collections.filter(t=>t.has(e))}toggleDiagnostic(){let{enabled:e}=this;this.enabled=!e;for(let t of this.buffers.items)if(this.enabled){let i=this.getDiagnostics(t.uri);t.forceRefresh(i)}else t.clear()}refreshBuffer(e,t=!1){if(!this.enabled)return!1;let i=this.buffers.getItem(e);if(!i)return!1;let n=this.getDiagnostics(i.uri);return t?i.forceRefresh(n):i.refresh(n),!0}},St=new Qj;var ht;(function(r){r[r.Null=0]="Null",r[r.Backspace=8]="Backspace",r[r.Tab=9]="Tab",r[r.LineFeed=10]="LineFeed",r[r.CarriageReturn=13]="CarriageReturn",r[r.Space=32]="Space",r[r.ExclamationMark=33]="ExclamationMark",r[r.DoubleQuote=34]="DoubleQuote",r[r.Hash=35]="Hash",r[r.DollarSign=36]="DollarSign",r[r.PercentSign=37]="PercentSign",r[r.Ampersand=38]="Ampersand",r[r.SingleQuote=39]="SingleQuote",r[r.OpenParen=40]="OpenParen",r[r.CloseParen=41]="CloseParen",r[r.Asterisk=42]="Asterisk",r[r.Plus=43]="Plus",r[r.Comma=44]="Comma",r[r.Dash=45]="Dash",r[r.Period=46]="Period",r[r.Slash=47]="Slash",r[r.Digit0=48]="Digit0",r[r.Digit1=49]="Digit1",r[r.Digit2=50]="Digit2",r[r.Digit3=51]="Digit3",r[r.Digit4=52]="Digit4",r[r.Digit5=53]="Digit5",r[r.Digit6=54]="Digit6",r[r.Digit7=55]="Digit7",r[r.Digit8=56]="Digit8",r[r.Digit9=57]="Digit9",r[r.Colon=58]="Colon",r[r.Semicolon=59]="Semicolon",r[r.LessThan=60]="LessThan",r[r.Equals=61]="Equals",r[r.GreaterThan=62]="GreaterThan",r[r.QuestionMark=63]="QuestionMark",r[r.AtSign=64]="AtSign",r[r.A=65]="A",r[r.B=66]="B",r[r.C=67]="C",r[r.D=68]="D",r[r.E=69]="E",r[r.F=70]="F",r[r.G=71]="G",r[r.H=72]="H",r[r.I=73]="I",r[r.J=74]="J",r[r.K=75]="K",r[r.L=76]="L",r[r.M=77]="M",r[r.N=78]="N",r[r.O=79]="O",r[r.P=80]="P",r[r.Q=81]="Q",r[r.R=82]="R",r[r.S=83]="S",r[r.T=84]="T",r[r.U=85]="U",r[r.V=86]="V",r[r.W=87]="W",r[r.X=88]="X",r[r.Y=89]="Y",r[r.Z=90]="Z",r[r.OpenSquareBracket=91]="OpenSquareBracket",r[r.Backslash=92]="Backslash",r[r.CloseSquareBracket=93]="CloseSquareBracket",r[r.Caret=94]="Caret",r[r.Underline=95]="Underline",r[r.BackTick=96]="BackTick",r[r.a=97]="a",r[r.b=98]="b",r[r.c=99]="c",r[r.d=100]="d",r[r.e=101]="e",r[r.f=102]="f",r[r.g=103]="g",r[r.h=104]="h",r[r.i=105]="i",r[r.j=106]="j",r[r.k=107]="k",r[r.l=108]="l",r[r.m=109]="m",r[r.n=110]="n",r[r.o=111]="o",r[r.p=112]="p",r[r.q=113]="q",r[r.r=114]="r",r[r.s=115]="s",r[r.t=116]="t",r[r.u=117]="u",r[r.v=118]="v",r[r.w=119]="w",r[r.x=120]="x",r[r.y=121]="y",r[r.z=122]="z",r[r.OpenCurlyBrace=123]="OpenCurlyBrace",r[r.Pipe=124]="Pipe",r[r.CloseCurlyBrace=125]="CloseCurlyBrace",r[r.Tilde=126]="Tilde",r[r.U_Combining_Grave_Accent=768]="U_Combining_Grave_Accent",r[r.U_Combining_Acute_Accent=769]="U_Combining_Acute_Accent",r[r.U_Combining_Circumflex_Accent=770]="U_Combining_Circumflex_Accent",r[r.U_Combining_Tilde=771]="U_Combining_Tilde",r[r.U_Combining_Macron=772]="U_Combining_Macron",r[r.U_Combining_Overline=773]="U_Combining_Overline",r[r.U_Combining_Breve=774]="U_Combining_Breve",r[r.U_Combining_Dot_Above=775]="U_Combining_Dot_Above",r[r.U_Combining_Diaeresis=776]="U_Combining_Diaeresis",r[r.U_Combining_Hook_Above=777]="U_Combining_Hook_Above",r[r.U_Combining_Ring_Above=778]="U_Combining_Ring_Above",r[r.U_Combining_Double_Acute_Accent=779]="U_Combining_Double_Acute_Accent",r[r.U_Combining_Caron=780]="U_Combining_Caron",r[r.U_Combining_Vertical_Line_Above=781]="U_Combining_Vertical_Line_Above",r[r.U_Combining_Double_Vertical_Line_Above=782]="U_Combining_Double_Vertical_Line_Above",r[r.U_Combining_Double_Grave_Accent=783]="U_Combining_Double_Grave_Accent",r[r.U_Combining_Candrabindu=784]="U_Combining_Candrabindu",r[r.U_Combining_Inverted_Breve=785]="U_Combining_Inverted_Breve",r[r.U_Combining_Turned_Comma_Above=786]="U_Combining_Turned_Comma_Above",r[r.U_Combining_Comma_Above=787]="U_Combining_Comma_Above",r[r.U_Combining_Reversed_Comma_Above=788]="U_Combining_Reversed_Comma_Above",r[r.U_Combining_Comma_Above_Right=789]="U_Combining_Comma_Above_Right",r[r.U_Combining_Grave_Accent_Below=790]="U_Combining_Grave_Accent_Below",r[r.U_Combining_Acute_Accent_Below=791]="U_Combining_Acute_Accent_Below",r[r.U_Combining_Left_Tack_Below=792]="U_Combining_Left_Tack_Below",r[r.U_Combining_Right_Tack_Below=793]="U_Combining_Right_Tack_Below",r[r.U_Combining_Left_Angle_Above=794]="U_Combining_Left_Angle_Above",r[r.U_Combining_Horn=795]="U_Combining_Horn",r[r.U_Combining_Left_Half_Ring_Below=796]="U_Combining_Left_Half_Ring_Below",r[r.U_Combining_Up_Tack_Below=797]="U_Combining_Up_Tack_Below",r[r.U_Combining_Down_Tack_Below=798]="U_Combining_Down_Tack_Below",r[r.U_Combining_Plus_Sign_Below=799]="U_Combining_Plus_Sign_Below",r[r.U_Combining_Minus_Sign_Below=800]="U_Combining_Minus_Sign_Below",r[r.U_Combining_Palatalized_Hook_Below=801]="U_Combining_Palatalized_Hook_Below",r[r.U_Combining_Retroflex_Hook_Below=802]="U_Combining_Retroflex_Hook_Below",r[r.U_Combining_Dot_Below=803]="U_Combining_Dot_Below",r[r.U_Combining_Diaeresis_Below=804]="U_Combining_Diaeresis_Below",r[r.U_Combining_Ring_Below=805]="U_Combining_Ring_Below",r[r.U_Combining_Comma_Below=806]="U_Combining_Comma_Below",r[r.U_Combining_Cedilla=807]="U_Combining_Cedilla",r[r.U_Combining_Ogonek=808]="U_Combining_Ogonek",r[r.U_Combining_Vertical_Line_Below=809]="U_Combining_Vertical_Line_Below",r[r.U_Combining_Bridge_Below=810]="U_Combining_Bridge_Below",r[r.U_Combining_Inverted_Double_Arch_Below=811]="U_Combining_Inverted_Double_Arch_Below",r[r.U_Combining_Caron_Below=812]="U_Combining_Caron_Below",r[r.U_Combining_Circumflex_Accent_Below=813]="U_Combining_Circumflex_Accent_Below",r[r.U_Combining_Breve_Below=814]="U_Combining_Breve_Below",r[r.U_Combining_Inverted_Breve_Below=815]="U_Combining_Inverted_Breve_Below",r[r.U_Combining_Tilde_Below=816]="U_Combining_Tilde_Below",r[r.U_Combining_Macron_Below=817]="U_Combining_Macron_Below",r[r.U_Combining_Low_Line=818]="U_Combining_Low_Line",r[r.U_Combining_Double_Low_Line=819]="U_Combining_Double_Low_Line",r[r.U_Combining_Tilde_Overlay=820]="U_Combining_Tilde_Overlay",r[r.U_Combining_Short_Stroke_Overlay=821]="U_Combining_Short_Stroke_Overlay",r[r.U_Combining_Long_Stroke_Overlay=822]="U_Combining_Long_Stroke_Overlay",r[r.U_Combining_Short_Solidus_Overlay=823]="U_Combining_Short_Solidus_Overlay",r[r.U_Combining_Long_Solidus_Overlay=824]="U_Combining_Long_Solidus_Overlay",r[r.U_Combining_Right_Half_Ring_Below=825]="U_Combining_Right_Half_Ring_Below",r[r.U_Combining_Inverted_Bridge_Below=826]="U_Combining_Inverted_Bridge_Below",r[r.U_Combining_Square_Below=827]="U_Combining_Square_Below",r[r.U_Combining_Seagull_Below=828]="U_Combining_Seagull_Below",r[r.U_Combining_X_Above=829]="U_Combining_X_Above",r[r.U_Combining_Vertical_Tilde=830]="U_Combining_Vertical_Tilde",r[r.U_Combining_Double_Overline=831]="U_Combining_Double_Overline",r[r.U_Combining_Grave_Tone_Mark=832]="U_Combining_Grave_Tone_Mark",r[r.U_Combining_Acute_Tone_Mark=833]="U_Combining_Acute_Tone_Mark",r[r.U_Combining_Greek_Perispomeni=834]="U_Combining_Greek_Perispomeni",r[r.U_Combining_Greek_Koronis=835]="U_Combining_Greek_Koronis",r[r.U_Combining_Greek_Dialytika_Tonos=836]="U_Combining_Greek_Dialytika_Tonos",r[r.U_Combining_Greek_Ypogegrammeni=837]="U_Combining_Greek_Ypogegrammeni",r[r.U_Combining_Bridge_Above=838]="U_Combining_Bridge_Above",r[r.U_Combining_Equals_Sign_Below=839]="U_Combining_Equals_Sign_Below",r[r.U_Combining_Double_Vertical_Line_Below=840]="U_Combining_Double_Vertical_Line_Below",r[r.U_Combining_Left_Angle_Below=841]="U_Combining_Left_Angle_Below",r[r.U_Combining_Not_Tilde_Above=842]="U_Combining_Not_Tilde_Above",r[r.U_Combining_Homothetic_Above=843]="U_Combining_Homothetic_Above",r[r.U_Combining_Almost_Equal_To_Above=844]="U_Combining_Almost_Equal_To_Above",r[r.U_Combining_Left_Right_Arrow_Below=845]="U_Combining_Left_Right_Arrow_Below",r[r.U_Combining_Upwards_Arrow_Below=846]="U_Combining_Upwards_Arrow_Below",r[r.U_Combining_Grapheme_Joiner=847]="U_Combining_Grapheme_Joiner",r[r.U_Combining_Right_Arrowhead_Above=848]="U_Combining_Right_Arrowhead_Above",r[r.U_Combining_Left_Half_Ring_Above=849]="U_Combining_Left_Half_Ring_Above",r[r.U_Combining_Fermata=850]="U_Combining_Fermata",r[r.U_Combining_X_Below=851]="U_Combining_X_Below",r[r.U_Combining_Left_Arrowhead_Below=852]="U_Combining_Left_Arrowhead_Below",r[r.U_Combining_Right_Arrowhead_Below=853]="U_Combining_Right_Arrowhead_Below",r[r.U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below=854]="U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below",r[r.U_Combining_Right_Half_Ring_Above=855]="U_Combining_Right_Half_Ring_Above",r[r.U_Combining_Dot_Above_Right=856]="U_Combining_Dot_Above_Right",r[r.U_Combining_Asterisk_Below=857]="U_Combining_Asterisk_Below",r[r.U_Combining_Double_Ring_Below=858]="U_Combining_Double_Ring_Below",r[r.U_Combining_Zigzag_Above=859]="U_Combining_Zigzag_Above",r[r.U_Combining_Double_Breve_Below=860]="U_Combining_Double_Breve_Below",r[r.U_Combining_Double_Breve=861]="U_Combining_Double_Breve",r[r.U_Combining_Double_Macron=862]="U_Combining_Double_Macron",r[r.U_Combining_Double_Macron_Below=863]="U_Combining_Double_Macron_Below",r[r.U_Combining_Double_Tilde=864]="U_Combining_Double_Tilde",r[r.U_Combining_Double_Inverted_Breve=865]="U_Combining_Double_Inverted_Breve",r[r.U_Combining_Double_Rightwards_Arrow_Below=866]="U_Combining_Double_Rightwards_Arrow_Below",r[r.U_Combining_Latin_Small_Letter_A=867]="U_Combining_Latin_Small_Letter_A",r[r.U_Combining_Latin_Small_Letter_E=868]="U_Combining_Latin_Small_Letter_E",r[r.U_Combining_Latin_Small_Letter_I=869]="U_Combining_Latin_Small_Letter_I",r[r.U_Combining_Latin_Small_Letter_O=870]="U_Combining_Latin_Small_Letter_O",r[r.U_Combining_Latin_Small_Letter_U=871]="U_Combining_Latin_Small_Letter_U",r[r.U_Combining_Latin_Small_Letter_C=872]="U_Combining_Latin_Small_Letter_C",r[r.U_Combining_Latin_Small_Letter_D=873]="U_Combining_Latin_Small_Letter_D",r[r.U_Combining_Latin_Small_Letter_H=874]="U_Combining_Latin_Small_Letter_H",r[r.U_Combining_Latin_Small_Letter_M=875]="U_Combining_Latin_Small_Letter_M",r[r.U_Combining_Latin_Small_Letter_R=876]="U_Combining_Latin_Small_Letter_R",r[r.U_Combining_Latin_Small_Letter_T=877]="U_Combining_Latin_Small_Letter_T",r[r.U_Combining_Latin_Small_Letter_V=878]="U_Combining_Latin_Small_Letter_V",r[r.U_Combining_Latin_Small_Letter_X=879]="U_Combining_Latin_Small_Letter_X",r[r.LINE_SEPARATOR_2028=8232]="LINE_SEPARATOR_2028",r[r.U_CIRCUMFLEX=94]="U_CIRCUMFLEX",r[r.U_GRAVE_ACCENT=96]="U_GRAVE_ACCENT",r[r.U_DIAERESIS=168]="U_DIAERESIS",r[r.U_MACRON=175]="U_MACRON",r[r.U_ACUTE_ACCENT=180]="U_ACUTE_ACCENT",r[r.U_CEDILLA=184]="U_CEDILLA",r[r.U_MODIFIER_LETTER_LEFT_ARROWHEAD=706]="U_MODIFIER_LETTER_LEFT_ARROWHEAD",r[r.U_MODIFIER_LETTER_RIGHT_ARROWHEAD=707]="U_MODIFIER_LETTER_RIGHT_ARROWHEAD",r[r.U_MODIFIER_LETTER_UP_ARROWHEAD=708]="U_MODIFIER_LETTER_UP_ARROWHEAD",r[r.U_MODIFIER_LETTER_DOWN_ARROWHEAD=709]="U_MODIFIER_LETTER_DOWN_ARROWHEAD",r[r.U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING=722]="U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING",r[r.U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING=723]="U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING",r[r.U_MODIFIER_LETTER_UP_TACK=724]="U_MODIFIER_LETTER_UP_TACK",r[r.U_MODIFIER_LETTER_DOWN_TACK=725]="U_MODIFIER_LETTER_DOWN_TACK",r[r.U_MODIFIER_LETTER_PLUS_SIGN=726]="U_MODIFIER_LETTER_PLUS_SIGN",r[r.U_MODIFIER_LETTER_MINUS_SIGN=727]="U_MODIFIER_LETTER_MINUS_SIGN",r[r.U_BREVE=728]="U_BREVE",r[r.U_DOT_ABOVE=729]="U_DOT_ABOVE",r[r.U_RING_ABOVE=730]="U_RING_ABOVE",r[r.U_OGONEK=731]="U_OGONEK",r[r.U_SMALL_TILDE=732]="U_SMALL_TILDE",r[r.U_DOUBLE_ACUTE_ACCENT=733]="U_DOUBLE_ACUTE_ACCENT",r[r.U_MODIFIER_LETTER_RHOTIC_HOOK=734]="U_MODIFIER_LETTER_RHOTIC_HOOK",r[r.U_MODIFIER_LETTER_CROSS_ACCENT=735]="U_MODIFIER_LETTER_CROSS_ACCENT",r[r.U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR=741]="U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR",r[r.U_MODIFIER_LETTER_HIGH_TONE_BAR=742]="U_MODIFIER_LETTER_HIGH_TONE_BAR",r[r.U_MODIFIER_LETTER_MID_TONE_BAR=743]="U_MODIFIER_LETTER_MID_TONE_BAR",r[r.U_MODIFIER_LETTER_LOW_TONE_BAR=744]="U_MODIFIER_LETTER_LOW_TONE_BAR",r[r.U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR=745]="U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR",r[r.U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK=746]="U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK",r[r.U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK=747]="U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK",r[r.U_MODIFIER_LETTER_UNASPIRATED=749]="U_MODIFIER_LETTER_UNASPIRATED",r[r.U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD=751]="U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD",r[r.U_MODIFIER_LETTER_LOW_UP_ARROWHEAD=752]="U_MODIFIER_LETTER_LOW_UP_ARROWHEAD",r[r.U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD=753]="U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD",r[r.U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD=754]="U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD",r[r.U_MODIFIER_LETTER_LOW_RING=755]="U_MODIFIER_LETTER_LOW_RING",r[r.U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT=756]="U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT",r[r.U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT=757]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT",r[r.U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT=758]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT",r[r.U_MODIFIER_LETTER_LOW_TILDE=759]="U_MODIFIER_LETTER_LOW_TILDE",r[r.U_MODIFIER_LETTER_RAISED_COLON=760]="U_MODIFIER_LETTER_RAISED_COLON",r[r.U_MODIFIER_LETTER_BEGIN_HIGH_TONE=761]="U_MODIFIER_LETTER_BEGIN_HIGH_TONE",r[r.U_MODIFIER_LETTER_END_HIGH_TONE=762]="U_MODIFIER_LETTER_END_HIGH_TONE",r[r.U_MODIFIER_LETTER_BEGIN_LOW_TONE=763]="U_MODIFIER_LETTER_BEGIN_LOW_TONE",r[r.U_MODIFIER_LETTER_END_LOW_TONE=764]="U_MODIFIER_LETTER_END_LOW_TONE",r[r.U_MODIFIER_LETTER_SHELF=765]="U_MODIFIER_LETTER_SHELF",r[r.U_MODIFIER_LETTER_OPEN_SHELF=766]="U_MODIFIER_LETTER_OPEN_SHELF",r[r.U_MODIFIER_LETTER_LOW_LEFT_ARROW=767]="U_MODIFIER_LETTER_LOW_LEFT_ARROW",r[r.U_GREEK_LOWER_NUMERAL_SIGN=885]="U_GREEK_LOWER_NUMERAL_SIGN",r[r.U_GREEK_TONOS=900]="U_GREEK_TONOS",r[r.U_GREEK_DIALYTIKA_TONOS=901]="U_GREEK_DIALYTIKA_TONOS",r[r.U_GREEK_KORONIS=8125]="U_GREEK_KORONIS",r[r.U_GREEK_PSILI=8127]="U_GREEK_PSILI",r[r.U_GREEK_PERISPOMENI=8128]="U_GREEK_PERISPOMENI",r[r.U_GREEK_DIALYTIKA_AND_PERISPOMENI=8129]="U_GREEK_DIALYTIKA_AND_PERISPOMENI",r[r.U_GREEK_PSILI_AND_VARIA=8141]="U_GREEK_PSILI_AND_VARIA",r[r.U_GREEK_PSILI_AND_OXIA=8142]="U_GREEK_PSILI_AND_OXIA",r[r.U_GREEK_PSILI_AND_PERISPOMENI=8143]="U_GREEK_PSILI_AND_PERISPOMENI",r[r.U_GREEK_DASIA_AND_VARIA=8157]="U_GREEK_DASIA_AND_VARIA",r[r.U_GREEK_DASIA_AND_OXIA=8158]="U_GREEK_DASIA_AND_OXIA",r[r.U_GREEK_DASIA_AND_PERISPOMENI=8159]="U_GREEK_DASIA_AND_PERISPOMENI",r[r.U_GREEK_DIALYTIKA_AND_VARIA=8173]="U_GREEK_DIALYTIKA_AND_VARIA",r[r.U_GREEK_DIALYTIKA_AND_OXIA=8174]="U_GREEK_DIALYTIKA_AND_OXIA",r[r.U_GREEK_VARIA=8175]="U_GREEK_VARIA",r[r.U_GREEK_OXIA=8189]="U_GREEK_OXIA",r[r.U_GREEK_DASIA=8190]="U_GREEK_DASIA",r[r.U_OVERLINE=8254]="U_OVERLINE",r[r.UTF8_BOM=65279]="UTF8_BOM"})(ht||(ht={}));var PAe=j()("snippets-parser"),G;(function(r){r[r.Dollar=0]="Dollar",r[r.Colon=1]="Colon",r[r.Comma=2]="Comma",r[r.CurlyOpen=3]="CurlyOpen",r[r.CurlyClose=4]="CurlyClose",r[r.Backslash=5]="Backslash",r[r.Forwardslash=6]="Forwardslash",r[r.Pipe=7]="Pipe",r[r.Int=8]="Int",r[r.VariableName=9]="VariableName",r[r.Format=10]="Format",r[r.Plus=11]="Plus",r[r.Dash=12]="Dash",r[r.QuestionMark=13]="QuestionMark",r[r.EOF=14]="EOF"})(G||(G={}));var en=class{static isDigitCharacter(e){return e>=ht.Digit0&&e<=ht.Digit9}static isVariableCharacter(e){return e===ht.Underline||e>=ht.a&&e<=ht.z||e>=ht.A&&e<=ht.Z}constructor(){this.text("")}text(e){this.value=e,this.pos=0}tokenText(e){return this.value.substr(e.pos,e.len)}next(){if(this.pos>=this.value.length)return{type:14,pos:this.pos,len:0};let e=this.pos,t=0,i=this.value.charCodeAt(e),n;if(n=en._table[i],typeof n=="number")return this.pos+=1,{type:n,pos:e,len:1};if(en.isDigitCharacter(i)){n=8;do t+=1,i=this.value.charCodeAt(e+t);while(en.isDigitCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}if(en.isVariableCharacter(i)){n=9;do i=this.value.charCodeAt(e+ ++t);while(en.isVariableCharacter(i)||en.isDigitCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}n=10;do t+=1,i=this.value.charCodeAt(e+t);while(!isNaN(i)&&typeof en._table[i]=="undefined"&&!en.isDigitCharacter(i)&&!en.isVariableCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}},_0=en;_0._table={[ht.DollarSign]:0,[ht.Colon]:1,[ht.Comma]:2,[ht.OpenCurlyBrace]:3,[ht.CloseCurlyBrace]:4,[ht.Backslash]:5,[ht.Slash]:6,[ht.Pipe]:7,[ht.Plus]:11,[ht.Dash]:12,[ht.QuestionMark]:13};var ra=class{constructor(){this._children=[]}appendChild(e){return e instanceof ut&&this._children[this._children.length-1]instanceof ut?this._children[this._children.length-1].value+=e.value:(e.parent=this,this._children.push(e)),this}setOnlyChild(e){e.parent=this,this._children=[e]}replace(e,t){let{parent:i}=e,n=i.children.indexOf(e),o=i.children.slice(0);o.splice(n,1,...t),i._children=o,function s(a,l){for(let u of a)u.parent=l,s(u.children,u)}(t,i)}get children(){return this._children}get snippet(){let e=this;for(;;){if(!e)return;if(e instanceof ap)return e;e=e.parent}}toString(){return this.children.reduce((e,t)=>e+t.toString(),"")}len(){return 0}get next(){let{parent:e}=this,{children:t}=e,i=t.indexOf(this);return t[i+1]}},ut=class extends ra{constructor(e){super();this.value=e}static escape(e){return e.replace(/\$|}|\\/g,"\\$&")}toString(){return this.value}toTextmateString(){return ut.escape(this.value)}len(){return this.value.length}clone(){return new ut(this.value)}},P0=class extends ra{},ei=class extends P0{constructor(e){super();this.index=e}static compareByIndex(e,t){return e.index===t.index?0:e.isFinalTabstop?1:t.isFinalTabstop||e.indext.index?1:0}get isFinalTabstop(){return this.index===0}get choice(){return this._children.length===1&&this._children[0]instanceof lp?this._children[0]:void 0}toTextmateString(){let e="";return this.transform&&(e=this.transform.toTextmateString()),this.children.length===0&&!this.transform?`$${this.index}`:this.children.length===0?`\${${this.index}${e}}`:this.choice?`\${${this.index}|${this.choice.toTextmateString()}|${e}}`:`\${${this.index}:${this.children.map(t=>t.toTextmateString()).join("")}${e}}`}clone(){let e=new ei(this.index);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(t=>t.clone()),e}},lp=class extends ra{constructor(){super(...arguments);this.options=[]}appendChild(e){return e instanceof ut&&(e.parent=this,this.options.push(e)),this}toString(){return this.options[0].value}toTextmateString(){return this.options.map(e=>e.value.replace(/\||,/g,"\\$&")).join(",")}len(){return this.options[0].len()}clone(){let e=new lp;for(let t of this.options)e.appendChild(t);return e}},dg=class extends ra{resolve(e){let t=!1,i=e.replace(this.regexp,(...n)=>(t=!0,this._replace(n.slice(0,-2))));return!t&&this._children.some(n=>n instanceof Pi&&Boolean(n.elseValue))&&(i=this._replace([])),i}_replace(e){let t="";for(let i of this._children)if(i instanceof Pi){let n=e[i.index]||"";n=i.resolve(n),t+=n}else t+=i.toString();return t}toString(){return""}toTextmateString(){return`/${this.regexp.source}/${this.children.map(e=>e.toTextmateString())}/${(this.regexp.ignoreCase?"i":"")+(this.regexp.global?"g":"")}`}clone(){let e=new dg;return e.regexp=new RegExp(this.regexp.source,""+(this.regexp.ignoreCase?"i":"")+(this.regexp.global?"g":"")),e._children=this.children.map(t=>t.clone()),e}},Pi=class extends ra{constructor(e,t,i,n){super();this.index=e;this.shorthandName=t;this.ifValue=i;this.elseValue=n}resolve(e){return this.shorthandName==="upcase"?e?e.toLocaleUpperCase():"":this.shorthandName==="downcase"?e?e.toLocaleLowerCase():"":this.shorthandName==="capitalize"?e?e[0].toLocaleUpperCase()+e.substr(1):"":this.shorthandName==="pascalcase"?e?this._toPascalCase(e):"":Boolean(e)&&typeof this.ifValue=="string"?this.ifValue:!e&&typeof this.elseValue=="string"?this.elseValue:e||""}_toPascalCase(e){let t=e.match(/[a-z]+/gi);return t?t.map(i=>i.charAt(0).toUpperCase()+i.substr(1).toLowerCase()).join(""):e}toTextmateString(){let e="${";return e+=this.index,this.shorthandName?e+=`:/${this.shorthandName}`:this.ifValue&&this.elseValue?e+=`:?${this.ifValue}:${this.elseValue}`:this.ifValue?e+=`:+${this.ifValue}`:this.elseValue&&(e+=`:-${this.elseValue}`),e+="}",e}clone(){return new Pi(this.index,this.shorthandName,this.ifValue,this.elseValue)}},yn=class extends P0{constructor(e){super();this.name=e}async resolve(e){let t=await e.resolve(this);if(t&&t.includes(` +`)){let i="";this.snippet.walk(l=>{if(l==this)return!1;if(l instanceof ut){let u=l.toString().split(/\r?\n/);i=u[u.length-1].match(/^\s*/)[0]}return!0});let n=t.split(` +`),o=n.filter(l=>l.length>0).map(l=>l.match(/^\s*/)[0]),s=o.length==0?"":o.reduce((l,u)=>l.lengthu==0||l.length==0||!l.startsWith(s)?l:i+l.slice(s.length)).join(` +`)}return this.transform&&(t=this.transform.resolve(t||"")),t!==void 0?(this._children=[new ut(t)],!0):!1}toTextmateString(){let e="";return this.transform&&(e=this.transform.toTextmateString()),this.children.length===0?`\${${this.name}${e}}`:`\${${this.name}:${this.children.map(t=>t.toTextmateString()).join("")}${e}}`}clone(){let e=new yn(this.name);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(t=>t.clone()),e}};function eU(r,e){let t=[...r];for(;t.length>0;){let i=t.shift();if(!e(i))break;t.unshift(...i.children)}}var ap=class extends ra{get placeholderInfo(){if(!this._placeholders){this._variables=[];let e=[],t;this.walk(i=>{if(i instanceof ei)e.push(i),t=!t||t.index90)&&this._variables.push(i)}return!0}),this._placeholders={all:e,last:t}}return this._placeholders}get variables(){return this._variables}get placeholders(){let{all:e}=this.placeholderInfo;return e}get maxIndexNumber(){let{placeholders:e}=this;return e.reduce((t,i)=>Math.max(t,i.index),0)}get minIndexNumber(){let{placeholders:e}=this,t=e.map(i=>i.index);return t.sort((i,n)=>i-n),t.length>1&&t[0]==0?t[1]:t[0]||0}insertSnippet(e,t,i){let n=this.placeholders[t];if(!n)return;let{index:o}=n,s=kt.create("untitled:/1","snippet",0,n.toString());e=kt.applyEdits(s,[{range:i,newText:e}]);let a=new Ho().parse(e,!0),l=a.maxIndexNumber+1,u=[];for(let c of a.placeholders)c.isFinalTabstop?c.index=l+o:c.index=c.index+o,u.push(c.index);return this.walk(c=>(c instanceof ei&&c.index>o&&(c.index=c.index+l),!0)),this.replace(n,a.children),Math.min.apply(null,u)}updatePlaceholder(e,t){let i=this.placeholders[e];for(let n of this.placeholders)if(n.index==i.index){let o=n.children[0],s=n.transform?n.transform.resolve(t):t;o?n.setOnlyChild(new ut(s)):n.appendChild(new ut(s))}this._placeholders=void 0}updateVariable(e,t){let i=this.variables[e-this.maxIndexNumber-1];if(i){let n=this.variables.filter(o=>o.name==i.name);for(let o of n){let s=o.transform?o.transform.resolve(t):t;o.setOnlyChild(new ut(s))}}}getPlaceholderText(e,t){let i=this.placeholders[e];return i&&i.transform?i.transform.resolve(t):t}offset(e){let t=0,i=!1;return this.walk(n=>n===e?(i=!0,!1):(t+=n.len(),!0)),i?t:-1}fullLen(e){let t=0;return eU([e],i=>(t+=i.len(),!0)),t}enclosingPlaceholders(e){let t=[],{parent:i}=e;for(;i;)i instanceof ei&&t.push(i),i=i.parent;return t}async resolveVariables(e){let t=[];this.walk(i=>(i instanceof yn&&t.push(i),!0)),await Promise.all(t.map(i=>i.resolve(e)))}appendChild(e){return this._placeholders=void 0,super.appendChild(e)}replace(e,t){return this._placeholders=void 0,super.replace(e,t)}toTextmateString(){return this.children.reduce((e,t)=>e+t.toTextmateString(),"")}clone(){let e=new ap;return this._children=this.children.map(t=>t.clone()),e}walk(e){eU(this.children,e)}},Ho=class{constructor(){this._scanner=new _0}static escape(e){return e.replace(/\$|}|\\/g,"\\$&")}text(e){return this.parse(e).toString()}parse(e,t){this._scanner.text(e),this._token=this._scanner.next();let i=new ap;for(;this._parse(i););let n=new Map,o=[];i.walk(s=>(s instanceof ei&&(s.isFinalTabstop?n.set(0,void 0):!n.has(s.index)&&s.children.length>0?n.set(s.index,s.children):o.push(s)),!0));for(let s of o)if(n.has(s.index)){let a=new ei(s.index);a.transform=s.transform;for(let l of n.get(s.index)){let u=l.clone();if(a.transform){if(u instanceof ut)u=new ut(a.transform.resolve(u.value));else for(let c of u.children)if(c instanceof ut){u.replace(c,[new ut(a.transform.resolve(c.value))]);break}}a.appendChild(u)}i.replace(s,[a])}return!n.has(0)&&t&&i.appendChild(new ei(0)),i}_accept(e,t){if(e===void 0||this._token.type===e){let i=t?this._scanner.tokenText(this._token):!0;return this._token=this._scanner.next(),i}return!1}_backTo(e){return this._scanner.pos=e.pos+e.len,this._token=e,!1}_until(e){if(this._token.type===14)return!1;let t=this._token;for(;this._token.type!==e;)if(this._token=this._scanner.next(),this._token.type===14)return!1;let i=this._scanner.value.substring(t.pos,this._token.pos);return this._token=this._scanner.next(),i}_parse(e){return this._parseEscaped(e)||this._parseTabstopOrVariableName(e)||this._parseComplexPlaceholder(e)||this._parseComplexVariable(e)||this._parseAnything(e)}_parseEscaped(e){let t;return(t=this._accept(5,!0))?(t=this._accept(0,!0)||this._accept(4,!0)||this._accept(5,!0)||t,e.appendChild(new ut(t)),!0):!1}_parseTabstopOrVariableName(e){let t,i=this._token;return this._accept(0)&&(t=this._accept(9,!0)||this._accept(8,!0))?(e.appendChild(/^\d+$/.test(t)?new ei(Number(t)):new yn(t)),!0):this._backTo(i)}_parseComplexPlaceholder(e){let t,i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(8,!0))))return this._backTo(i);let o=new ei(Number(t));if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new ut("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else if(o.index>0&&this._accept(7)){let s=new lp;for(;;){if(this._parseChoiceElement(s)){if(this._accept(2))continue;if(this._accept(7)&&(o.appendChild(s),this._accept(4)))return e.appendChild(o),!0}return this._backTo(i),!1}}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseChoiceElement(e){let t=this._token,i=[];for(;!(this._token.type===2||this._token.type===7);){let n;if((n=this._accept(5,!0))?n=this._accept(2,!0)||this._accept(7,!0)||this._accept(5,!0)||n:n=this._accept(void 0,!0),!n)return this._backTo(t),!1;i.push(n)}return i.length===0?(this._backTo(t),!1):(e.appendChild(new ut(i.join(""))),!0)}_parseComplexVariable(e){let t,i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(9,!0))))return this._backTo(i);let o=new yn(t);if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new ut("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseTransform(e){let t=new dg,i="",n="";for(;!this._accept(6);){let o;if(o=this._accept(5,!0)){o=this._accept(6,!0)||o,i+=o;continue}if(this._token.type!==14){i+=this._accept(void 0,!0);continue}return!1}for(;!this._accept(6);){let o;if(o=this._accept(5,!0)){o=this._accept(6,!0)||o,t.appendChild(new ut(o));continue}if(this._parseFormatString(t)||this._parseAnything(t)){let s=t.children[0];s&&s.value&&s.value.includes("\\n")&&(s.value=s.value.replace(/\\n/g,` +`));continue}return!1}for(;!this._accept(4);){if(this._token.type!==14){n+=this._accept(void 0,!0);continue}return!1}try{t.regexp=new RegExp(i,n)}catch(o){return!1}return e.transform=t,!0}_parseFormatString(e){let t=this._token;if(!this._accept(0))return!1;let i=!1;this._accept(3)&&(i=!0);let n=this._accept(8,!0);if(n)if(i){if(this._accept(4))return e.appendChild(new Pi(Number(n))),!0;if(!this._accept(1))return this._backTo(t),!1}else return e.appendChild(new Pi(Number(n))),!0;else return this._backTo(t),!1;if(this._accept(6)){let o=this._accept(9,!0);return!o||!this._accept(4)?(this._backTo(t),!1):(e.appendChild(new Pi(Number(n),o)),!0)}else if(this._accept(11)){let o=this._until(4);if(o)return e.appendChild(new Pi(Number(n),void 0,o,void 0)),!0}else if(this._accept(12)){let o=this._until(4);if(o)return e.appendChild(new Pi(Number(n),void 0,void 0,o)),!0}else if(this._accept(13)){let o=this._until(1);if(o){let s=this._until(4);if(s)return e.appendChild(new Pi(Number(n),void 0,o,s)),!0}}else{let o=this._until(4);if(o)return e.appendChild(new Pi(Number(n),void 0,void 0,o)),!0}return this._backTo(t),!1}_parseAnything(e){if(this._token.type!==14){let t=this._scanner.tokenText(this._token);return e.appendChild(new ut(t)),this._accept(void 0),!0}return!1}};var Lu=S(W());var $C=S(W());var l9=S(Bl()),u9=S(require("fs")),jv=S(require("path")),c9=S(require("util")),f9=S(W());var Vz=S(Gr());var st=S($i()),Kz=S(Ex()),Fe=S(require("path")),Jz=S(Pf()),Mv=S(W());var Yz=S(El());var tU=S(require("events"));var kAe=j()("model-installBuffer"),tn;(function(r){r[r.Waiting=0]="Waiting",r[r.Faild=1]="Faild",r[r.Progressing=2]="Progressing",r[r.Success=3]="Success"})(tn||(tn={}));var T0=class extends tU.EventEmitter{constructor(e=!1,t=!1,i=void 0){super();this.isUpdate=e;this.isSync=t;this.channel=i;this.statMap=new Map;this.messagesMap=new Map;this.names=[]}setExtensions(e){this.statMap.clear(),this.names=e;for(let t of e)this.statMap.set(t,0)}addMessage(e,t,i=!1){if(i&&this.channel)return;let n=this.messagesMap.get(e)||[];this.messagesMap.set(e,n.concat(t.trim().split(/\r?\n/))),this.channel&&this.channel.appendLine(`[${e}] ${t}`)}startProgress(e){for(let t of e)this.statMap.set(t,2)}finishProgress(e,t=!0){this.channel&&(t?this.channel.appendLine(`[${e}] install succeed!`):this.channel.appendLine(`[${e}] install failed!`)),this.statMap.set(e,t?3:1)}get remains(){let e=0;for(let t of this.names){let i=this.statMap.get(t);[3,1].includes(i)||(e=e+1)}return e}getLines(){let e=[];for(let t of this.names){let i=this.statMap.get(t),n="*";switch(i){case 2:{let s=new Date,a=Math.floor(s.getMilliseconds()/100);n=PD[a];break}case 1:n="\u2717";break;case 3:n="\u2713";break}let o=this.messagesMap.get(t)||[];e.push(`- ${n} ${t} ${o.length?o[o.length-1]:""}`)}return e}getMessages(e){if(e<=1)return[];let t=this.names[e-2];return t?this.messagesMap.get(t):[]}draw(e,t){let{remains:i}=this,o=[i==0?`${this.isUpdate?"Update":"Install"} finished`:`Installing, ${i} remains...`,"",...this.getLines()];t.setLines(o,{start:0,end:-1,strictIndexing:!1},!0),i==0&&this.interval&&(clearInterval(this.interval),this.interval=null),process.env.VIM_NODE_RPC&&e.command("redraw",!0)}highlight(e){e.call("matchadd",["CocListFgCyan","^\\-\\s\\zs\\*"],!0),e.call("matchadd",["CocListFgGreen","^\\-\\s\\zs\u2713"],!0),e.call("matchadd",["CocListFgRed","^\\-\\s\\zs\u2717"],!0),e.call("matchadd",["CocListFgYellow","^-.\\{3\\}\\zs\\S\\+"],!0)}async show(e){let{isSync:t}=this;if(this.channel)return;e.pauseNotification(),e.command(t?"enew":"vs +enew",!0),e.call("bufnr",["%"],!0),e.command("setl buftype=nofile bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1",!0),t||e.command("nnoremap q :q",!0),this.highlight(e);let i=await e.resumeNotification(),n=i&&i[1]==null?i[0][1]:null;if(!n)return;this.bufnr=n;let o=e.createBuffer(n);this.interval=setInterval(()=>{this.draw(e,o)},100)}dispose(){this.interval&&clearInterval(this.interval)}},R0=T0;var B5=S(require("events")),j5=S(require("child_process"));var U5=S(require("readline")),fr=S($i()),W5=S(require("os")),Sn=S(require("path")),H5=S(SU()),pv=S(Pf());var N5=S(FU()),cv=S(B0()),fv=S($i()),$p=S(require("path")),q5=S(kW()),$5=S(c5());var uv=S(B0()),hE=S(require("url")),I5=S(require("fs"));var F5=S(require("querystring")),A5=S(b5()),O5=S(_5()),L5=S(k5()),M5=j()("model-fetch");function Zve(r){let e;r.protocol==="http:"?e=process.env.HTTP_PROXY||process.env.http_proxy||null:r.protocol==="https:"&&(e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||null);let t=process.env.NO_PROXY||process.env.no_proxy;if(t==="*")e=null;else if(t){let i=r.hostname.replace(/^\.*/,".").toLowerCase(),n=r.port||r.protocol.startsWith("https")?"443":"80",o=t.split(",");for(let s=0,a=o.length;s{if(i){let l=i.onCancellationRequested(()=>{l.dispose(),a.destroy(new Error("request aborted"))})}let a=n.request(t,l=>{let u=l;if(l.statusCode>=200&&l.statusCode<300||l.statusCode===1223){let c=l.headers||{},f=[],p=c["content-type"]||"";u=L5.default(l),u.on("data",d=>{f.push(d)}),u.on("end",()=>{let d=Buffer.concat(f);if(!t.buffer&&(p.startsWith("application/json")||p.startsWith("text/"))){let h=p.match(/charset=(\S+)/),m=h?h[1]:"utf8",y=d.toString(m);if(!p.includes("application/json"))o(y);else try{let v=JSON.parse(y);o(v)}catch(v){s(new Error(`Parse response error: ${v}`))}}else o(d)}),u.on("error",d=>{s(new Error(`Unable to connect ${r}: ${d.message}`))})}else s(new Error(`Bad response from ${r}: ${l.statusCode}`))});a.on("error",s),a.on("timeout",()=>{a.destroy(new Error(`Request timeout after ${t.timeout}ms`))}),e&&(typeof e=="string"||Buffer.isBuffer(e)?a.write(e):a.write(JSON.stringify(e))),t.timeout&&a.setTimeout(t.timeout),a.end()})}function eye(r){return r===null?"null":r===void 0?"undefined":typeof r=="string"?"string":Buffer.isBuffer(r)?"buffer":Array.isArray(r)||wt(r)?"object":"unknown"}function Cu(r,e={},t){let i=mE(r,e);return tye(r,e.data,i,t).catch(n=>{if(M5.error(`Fetch error for ${r}:`,i,n),i.agent&&i.agent.proxy){let{proxy:o}=i.agent;throw new Error(`Request failed using proxy ${o.host}: ${n.message}`)}else throw n})}var gE=j()("model-download");function Bp(r,e,t){let{dest:i,onProgress:n,extract:o}=e;if(!i||!$p.default.isAbsolute(i))throw new Error("Expect absolute file path for dest option.");let s;try{s=fv.default.statSync(i)}catch(c){fv.default.mkdirpSync(i)}if(s&&!s.isDirectory())throw new Error(`${i} exists, but not directory!`);let a=r.startsWith("https")?cv.https:cv.http,l=mE(r,e),u=$p.default.extname(r);return new Promise((c,f)=>{if(t){let d=t.onCancellationRequested(()=>{d.dispose(),p.destroy(new Error("request aborted"))})}let p=a.request(l,d=>{var h,m;if(d.statusCode>=200&&d.statusCode<300||d.statusCode===1223){let y=d.headers||{},v=y["content-disposition"];if(!u&&v){let P=N5.default.parse(v);((h=P.parameters)==null?void 0:h.filename)&&(u=$p.default.extname(P.parameters.filename))}if(o===!0)if(u===".zip"||y["content-type"]=="application/zip")o="unzip";else if(u==".tgz")o="untar";else{f(new Error(`Unable to extract for ${r}`));return}let x=Number(y["content-length"]),w=0;isNaN(x)||d.on("data",P=>{w+=P.length;let k=(w/x*100).toFixed(1);n?n(k):gE.info(`Download ${r} progress ${k}%`)}),d.on("error",P=>{f(new Error(`Unable to connect ${r}: ${P.message}`))}),d.on("end",()=>{gE.info("Download completed:",r)});let E;o==="untar"?E=d.pipe(q5.default.x({strip:(m=e.strip)!=null?m:1,C:i})):o==="unzip"?E=d.pipe($5.default.Extract({path:i})):(i=$p.default.join(i,`${qo()}${u}`),E=d.pipe(fv.default.createWriteStream(i))),E.on("finish",()=>{gE.info(`Downloaded ${r} => ${i}`),setTimeout(()=>{c(i)},100)}),E.on("error",f)}else f(new Error(`Invalid response from ${r}: ${d.statusCode}`))});p.on("error",f),p.on("timeout",()=>{p.destroy(new Error(`request timeout after ${e.timeout}ms`))}),e.timeout&&p.setTimeout(e.timeout),p.end()})}var z5=j()("model-installer");function rye(r="coc.nvim"){let e=H5.default("npm",{registry:"https://registry.npmjs.org/"}),t=e[`${r}:registry`]||e.config_registry||e.registry;return t.endsWith("/")?t:t+"/"}var G5=class extends B5.EventEmitter{constructor(e,t,i){super();this.root=e;this.npm=t;this.def=i;if(fr.default.existsSync(e)||fr.default.mkdirpSync(e),/^https?:/.test(i))this.url=i;else if(i.startsWith("@")){let n=i.indexOf("@",1);n>1?(this.name=i.substring(0,n),this.version=i.substring(n+1)):this.name=i}else if(i.includes("@")){let[n,o]=i.split("@",2);this.name=n,this.version=o}else this.name=i}get info(){return{name:this.name,version:this.version}}async install(){this.log(`Using npm from: ${this.npm}`);let e=await this.getInfo();z5.info(`Fetched info of ${this.def}`,e);let{name:t}=e,i=e["engines.coc"]?e["engines.coc"].replace(/^\^/,">="):"";if(i&&!pv.default.satisfies(b.version,i))throw new Error(`${t} ${e.version} requires coc.nvim >= ${i}, please update coc.nvim.`);return await this.doInstall(e),t}async update(e){this.url=e;let t=Sn.default.join(this.root,this.name);if((await fr.default.lstat(t)).isSymbolicLink()){this.log("Skipped update for symbol link");return}let n;if(fr.default.existsSync(Sn.default.join(t,"package.json"))){let l=await fr.default.readFile(Sn.default.join(t,"package.json"),"utf8");n=JSON.parse(l).version}this.log(`Using npm from: ${this.npm}`);let o=await this.getInfo();if(n&&o.version&&pv.default.gte(n,o.version)){this.log(`Current version ${n} is up to date.`);return}let s=o["engines.coc"]?o["engines.coc"].replace(/^\^/,">="):"";if(s&&!pv.default.satisfies(b.version,s))throw new Error(`${o.version} requires coc.nvim ${s}, please update coc.nvim.`);await this.doInstall(o);let a=Sn.default.join(this.root,o.name,"package.json");if(fr.default.existsSync(a))return this.log(`Updated to v${o.version}`),Sn.default.dirname(a);throw new Error(`Package.json not found: ${a}`)}async doInstall(e){let t=Sn.default.join(this.root,e.name);if(fr.default.existsSync(t)&&!fr.default.statSync(t).isDirectory()){this.log(`${t} is not directory skipped install`);return}let i=await fr.default.mkdtemp(Sn.default.join(W5.default.tmpdir(),`${e.name.replace("/","-")}-`)),n=e["dist.tarball"];this.log(`Downloading from ${n}`),await Bp(n,{dest:i,onProgress:p=>this.log(`Download progress ${p}%`,!0),extract:"untar"}),this.log(`Extension download at ${i}`);let o=await fr.default.readFile(Sn.default.join(i,"package.json"),"utf8"),{dependencies:s}=JSON.parse(o);s&&Object.keys(s).length&&await new Promise((d,h)=>{let m=["install","--ignore-scripts","--no-lockfile","--production"];n.startsWith("https://github.com")&&(m=["install"]),(this.npm.endsWith("npm")||this.npm.endsWith("npm.CMD"))&&!this.npm.endsWith("pnpm")&&m.push("--legacy-peer-deps"),this.npm.endsWith("yarn")&&m.push("--ignore-engines"),this.log(`Installing dependencies by: ${this.npm} ${m.join(" ")}.`);let y=j5.spawn(this.npm,m,{cwd:i});U5.default.createInterface({input:y.stdout}).on("line",w=>{this.log(`[npm] ${w}`,!0)}),y.stderr.setEncoding("utf8"),y.stdout.setEncoding("utf8"),y.on("error",h);let x="";y.stderr.on("data",w=>{x+=w}),y.on("exit",w=>{if(w){x&&this.log(x),h(new Error(`${this.npm} install exited with ${w}`));return}d()})});let a=Sn.default.resolve(this.root,global.hasOwnProperty("__TEST__")?"":"..","package.json"),l=[],u=Ul(fr.default.readFileSync(a,"utf8"),l,{allowTrailingComma:!0});if(l&&l.length>0)throw new Error(`Error on load ${a}`);u.dependencies=u.dependencies||{},this.url?u.dependencies[e.name]=this.url:u.dependencies[e.name]=">="+e.version;let c={dependencies:{}};Object.keys(u.dependencies).sort().forEach(p=>{c.dependencies[p]=u.dependencies[p]});let f=await Ht(t);f&&(f.isDirectory()?fr.default.removeSync(t):fr.default.unlinkSync(t)),await fr.default.move(i,t,{overwrite:!0}),await fr.default.writeFile(a,JSON.stringify(c,null,2),{encoding:"utf8"}),this.log(`Update package.json at ${a}`),this.log(`Installed extension ${this.name}@${e.version} at ${t}`)}async getInfo(){if(this.url)return await this.getInfoFromUri();let e=rye();this.log(`Get info from ${e}`);let t=await Cu(e+this.name,{timeout:1e4,buffer:!0}),i=JSON.parse(t.toString());this.version||(this.version=i["dist-tags"].latest);let n=i.versions[this.version];if(!n)throw new Error(`${this.def} doesn't exists in ${e}.`);let o=n.engines&&n.engines.coc;if(!o)throw new Error(`${this.def} is not valid coc extension, "engines" field with coc property required.`);return{"dist.tarball":n.dist.tarball,"engines.coc":o,version:n.version,name:i.name}}async getInfoFromUri(){let{url:e}=this;if(!e.includes("github.com"))throw new Error(`"${e}" is not supported, coc.nvim support github.com only`);e=e.replace(/\/$/,"");let t=e.replace("github.com","raw.githubusercontent.com")+"/master/package.json";this.log(`Get info from ${t}`);let i=await Cu(t,{timeout:1e4}),n=typeof i=="string"?JSON.parse(i):i;return this.name=n.name,{"dist.tarball":`${e}/archive/master.tar.gz`,"engines.coc":n.engines?n.engines.coc:null,name:n.name,version:n.version}}log(e,t=!1){z5.info(e),this.emit("message",e,t)}};function dv(r,e){return t=>new G5(e,r,t)}var _u=S(require("fs"));var iye=j()("model-memos"),vE=class{constructor(e){this.filepath=e;_u.default.existsSync(e)||_u.default.writeFileSync(e,"{}","utf8")}fetchContent(e,t){try{let i=_u.default.readFileSync(this.filepath,"utf8"),o=JSON.parse(i)[e];return o?o[t]:void 0}catch(i){return}}async update(e,t,i){let{filepath:n}=this;try{let o=_u.default.readFileSync(n,"utf8"),s=o?JSON.parse(o):{};s[e]=s[e]||{},i!==void 0?s[e][t]=zn(i):delete s[e][t],o=JSON.stringify(s,null,2),_u.default.writeFileSync(n,o,"utf8")}catch(o){iye.error("Error on update memos:",o)}}createMemento(e){return{get:(t,i)=>{let n=this.fetchContent(e,t);return n===void 0?i:n},update:async(t,i)=>{await this.update(e,t,i)}}}},V5=vE;var I4e=S(gh());var Wz=S(require("fs")),Hz=S(require("path")),Lv=S(require("vm"));var K5=Object.prototype,nye=K5.hasOwnProperty;function J5(r,...e){return r=Object(r),e.forEach(t=>{if(t!=null){t=Object(t);for(let i in t){let n=r[i];(n===void 0||n===K5[i]&&!nye.call(r,i))&&(r[i]=t[i])}}}),r}function xa(r,e){let t={};for(let i of Object.keys(r))e.includes(i)||(t[i]=r[i]);return t}var zz=j(),u4e=zz("util-factoroy"),Pn=require("module"),Wye=["reallyExit","abort","umask","setuid","setgid","setgroups","_fatalException","exit","kill"];function Hye(r){return()=>{throw new Error(`process.${r}() is not allowed in extension sandbox`)}}var ce=S(W());var hv=S(W());var Pu=S(W());var $Le=j()("provider-manager"),yE=class{constructor(){this.providers=new Set}hasProvider(e){return this.getProvider(e)!=null}getProvider(e){let t=0,i;for(let n of this.providers){let{selector:o,priority:s}=n,a=b.match(o,e);a!=0&&(typeof s=="number"&&(a=s),!(ai.id==e);return t?t.provider:null}getProviders(e){let t=Array.from(this.providers);return t=t.filter(i=>b.match(i.selector,e)>0),t.sort((i,n)=>b.match(n.selector,e)-b.match(i.selector,e))}toLocations(e){let t=[];for(let i of e)if(!!i)if(Pu.Location.is(i))t.push(i);else if(Array.isArray(i)){for(let n of i)if(Pu.Location.is(n))t.push(n);else if(Pu.LocationLink.is(n)){let{targetUri:o,targetSelectionRange:s}=n;t.push(Pu.Location.create(o,s))}}else C.showMessage(`Bad definition ${JSON.stringify(i)}`,"error");return t}},xe=yE;var JLe=j()("codeActionManager"),bE=class extends xe{register(e,t,i,n){let o={id:he(),selector:e,provider:t,kinds:n,clientId:i};return this.providers.add(o),hv.Disposable.create(()=>{this.providers.delete(o)})}async provideCodeActions(e,t,i,n){let o=this.getProviders(e);if(!o.length)return null;if(i.only){let{only:a}=i;o=o.filter(l=>!(l.kinds&&!l.kinds.some(u=>a.includes(u))))}let s=[];return await Promise.all(o.map(a=>{let{provider:l,clientId:u}=a;return Promise.resolve(l.provideCodeActions(e,t,i,n)).then(c=>{if(!(!c||c.length==0))for(let f of c)if(hv.Command.is(f)){let p={title:f.title,command:f,clientId:u};s.push(p)}else{if(i.only){if(!f.kind)continue;let d=!1;for(let h of i.only)if(f.kind.startsWith(h)){d=!0;break}if(!d)continue}s.findIndex(d=>d.title==f.title)==-1&&s.push(Object.assign({clientId:u},f))}})})),s}dispose(){this.providers=new Set}},Y5=bE;var X5=S(W());var wE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),X5.Disposable.create(()=>{this.providers.delete(i)})}async provideCodeLenses(e,t){let i=this.getProviders(e);if(!i.length)return null;let n=await Promise.all(i.map(o=>{let{provider:s,id:a}=o;return Promise.resolve(s.provideCodeLenses(e,t)).then(l=>{if(Array.isArray(l))for(let u of l)u.source=a;return l||[]})}));return[].concat(...n)}async resolveCodeLens(e,t){if(e.command)return e;let{source:i}=e,n=this.poviderById(i);if(!n||typeof n.resolveCodeLens!="function")return e;let o=await Promise.resolve(n.resolveCodeLens(xa(e,["source"]),t));return Object.assign(e,o),e}dispose(){this.providers=new Set}},Z5=wE;var Q5=S(W());var dMe=j()("definitionManager"),xE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),Q5.Disposable.create(()=>{this.providers.delete(i)})}async provideDeclaration(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;return await Promise.resolve(o.provideDeclaration(e,t,i))}dispose(){this.providers=new Set}},e4=xE;var t4=S(W());var DMe=j()("definitionManager"),DE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),t4.Disposable.create(()=>{this.providers.delete(i)})}async provideDefinition(e,t,i){let n=this.getProviders(e);if(!n.length)return null;let o=await Promise.all(n.map(s=>{let{provider:a}=s;return Promise.resolve(a.provideDefinition(e,t,i))}));return this.toLocations(o)}dispose(){this.providers=new Set}},r4=DE;var i4=S(W());var SE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),i4.Disposable.create(()=>{this.providers.delete(i)})}async provideDocumentColors(e,t){let i=this.getProvider(e);if(!i)return null;let{provider:n}=i;return await Promise.resolve(n.provideDocumentColors(e,t))}async provideColorPresentations(e,t,i){let{range:n,color:o}=e,s=this.getProvider(t);if(!s)return null;let{provider:a}=s;return await Promise.resolve(a.provideColorPresentations(o,{document:t,range:n},i))}dispose(){this.providers=new Set}},n4=SE;var o4=S(W());var EE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),o4.Disposable.create(()=>{this.providers.delete(i)})}async provideDocumentHighlights(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;return await Promise.resolve(o.provideDocumentHighlights(e,t,i))}dispose(){this.providers=new Set}},s4=EE;var a4=S(W());var CE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),a4.Disposable.create(()=>{this.providers.delete(i)})}async _provideDocumentLinks(e,t,i){let{provider:n,id:o}=e,s=await Promise.resolve(n.provideDocumentLinks(t,i));return!s||!s.length?[]:(s.forEach(a=>{a.data=a.data||{},a.data.source=o}),s)}async provideDocumentLinks(e,t){let i=this.getProviders(e);if(i.length==0)return[];let n=await Promise.all(i.map(o=>this._provideDocumentLinks(o,e,t)));return[].concat(...n)}async resolveDocumentLink(e,t){let{data:i}=e;if(!i||!i.source)return null;for(let n of this.providers)if(n.id==i.source){let{provider:o}=n;return e=await Promise.resolve(o.resolveDocumentLink(e,t)),e}return null}dispose(){this.providers=new Set}},l4=CE;var u4=S(W());var _E=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),u4.Disposable.create(()=>{this.providers.delete(i)})}async provideDocumentSymbols(e,t){let i=this.getProvider(e);if(!i)return null;let{provider:n}=i;return await Promise.resolve(n.provideDocumentSymbols(e,t))||[]}dispose(){this.providers=new Set}},c4=_E;var f4=S(W());var PE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),f4.Disposable.create(()=>{this.providers.delete(i)})}async provideFoldingRanges(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;return await Promise.resolve(o.provideFoldingRanges(e,t,i))||[]}dispose(){this.providers=new Set}},p4=PE;var d4=S(W());var TE=class extends xe{register(e,t,i=0){let n={id:he(),selector:e,priority:i,provider:t};return this.providers.add(n),d4.Disposable.create(()=>{this.providers.delete(n)})}handles(e){return this.getProvider(e)!=null}async provideDocumentFormattingEdits(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;return await Promise.resolve(o.provideDocumentFormattingEdits(e,t,i))}dispose(){this.providers=new Set}},h4=TE;var m4=S(W());var RE=class extends xe{register(e,t,i=0){let n={id:he(),selector:e,provider:t,priority:i};return this.providers.add(n),m4.Disposable.create(()=>{this.providers.delete(n)})}async provideDocumentRangeFormattingEdits(e,t,i,n){let o=this.getProvider(e);if(!o)return null;let{provider:s}=o;return await Promise.resolve(s.provideDocumentRangeFormattingEdits(e,t,i,n))}dispose(){this.providers=new Set}},g4=RE;var v4=S(W());var kE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),v4.Disposable.create(()=>{this.providers.delete(i)})}async provideHover(e,t,i){let n=this.getProviders(e);if(n.length===0)return null;let o=[];for(let s=0,a=n.length;s{this.providers.delete(i)})}async provideReferences(e,t,i){let n=this.getProviders(e);if(!n.length)return null;let o=await Promise.all(n.map(s=>{let{provider:a}=s;return Promise.resolve(a.provideImplementation(e,t,i))}));return this.toLocations(o)}dispose(){this.providers=new Set}},w4=IE;var x4=S(W());var GNe=j()("onTypeFormatManager"),FE=class{constructor(){this.providers=new Set}register(e,t,i){let n={triggerCharacters:i,selector:e,provider:t};return this.providers.add(n),x4.Disposable.create(()=>{this.providers.delete(n)})}hasProvider(e){for(let t of this.providers){let{selector:i}=t;if(b.match(i,e)>0)return!0}return!1}getProvider(e,t){for(let i of this.providers){let{triggerCharacters:n,selector:o}=i;if(b.match(o,e)>0&&n.includes(t))return i.provider}return null}async onCharacterType(e,t,i,n){let o=this.getProvider(t,e);if(!o)return;let s=await b.getFormatOptions(t.uri);return await Promise.resolve(o.provideOnTypeFormattingEdits(t,i,e,s,n))}dispose(){this.providers=new Set}},D4=FE;var S4=S(W());var AE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),S4.Disposable.create(()=>{this.providers.delete(i)})}async provideSelectionRanges(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;return await Promise.resolve(o.provideSelectionRanges(e,t,i))||[]}dispose(){this.providers=new Set}},E4=AE;var C4=S(W());var OE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),C4.Disposable.create(()=>{this.providers.delete(i)})}async provideReferences(e,t,i,n){let o=this.getProviders(e);if(!o.length)return null;let s=await Promise.all(o.map(a=>{let{provider:l}=a;return Promise.resolve(l.provideReferences(e,t,i,n))}));return this.toLocations(s)}dispose(){this.providers=new Set}},_4=OE;var P4=S(W());var LE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),P4.Disposable.create(()=>{this.providers.delete(i)})}async provideRenameEdits(e,t,i,n){let o=this.getProvider(e);if(!o)return null;let{provider:s}=o;return await Promise.resolve(s.provideRenameEdits(e,t,i,n))}async prepareRename(e,t,i){let n=this.getProvider(e);if(!n)return null;let{provider:o}=n;if(o.prepareRename==null)return null;let s=await Promise.resolve(o.prepareRename(e,t,i));return s==null?!1:s}dispose(){this.providers=new Set}},T4=LE;var R4=S(W());var ME=class extends xe{register(e,t,i){let n=i.reduce((s,a)=>s.concat(a.split(/\s*/g)),[]),o={id:he(),selector:e,provider:t,triggerCharacters:n};return this.providers.add(o),R4.Disposable.create(()=>{this.providers.delete(o)})}shouldTrigger(e,t){let i=this.getProvider(e);if(!i)return!1;let{triggerCharacters:n}=i;return n&&n.indexOf(t)!=-1}async provideSignatureHelp(e,t,i,n){let o=this.getProvider(e);if(!o)return null;let s=await Promise.resolve(o.provider.provideSignatureHelp(e,t,i,n));return s&&s.signatures&&s.signatures.length?s:null}dispose(){this.providers=new Set}},k4=ME;var I4=S(W());var NE=class extends xe{register(e,t){let i={id:he(),selector:e,provider:t};return this.providers.add(i),I4.Disposable.create(()=>{this.providers.delete(i)})}async provideTypeDefinition(e,t,i){let n=this.getProviders(e);if(!n.length)return null;let o=await Promise.all(n.map(s=>{let{provider:a}=s;return Promise.resolve(a.provideTypeDefinition(e,t,i))}));return this.toLocations(o)}dispose(){this.providers=new Set}},F4=NE;var A4=S(W()),qE=class{constructor(){this.providers=new Map}register(e){let t=he();return this.providers.set(t,e),A4.Disposable.create(()=>{this.providers.delete(t)})}async provideWorkspaceSymbols(e,t){let i=Array.from(this.providers.entries());if(!i.length)return[];let n=[];return await Promise.all(i.map(o=>{let[s,a]=o;return Promise.resolve(a.provideWorkspaceSymbols(e,t)).then(l=>{l&&(l.source=s,n.push(...l))})})),n}async resolveWorkspaceSymbol(e,t){let i=this.providers.get(e.source);if(!!i)return typeof i.resolveWorkspaceSymbol!="function"?Promise.resolve(e):await Promise.resolve(i.resolveWorkspaceSymbol(e,t))}hasProvider(){return this.providers.size>0}dispose(){this.providers=new Map}},O4=qE;var L4=S(W());var zqe=j()("util-complete");function M4(r){let{line:e,linenr:t,colnr:i}=r,n=Rt(e,0,i-1);return{line:t-1,character:n.length}}function q4(r,e,t){let{label:i,data:n,insertTextFormat:o,insertText:s,textEdit:a}=r,l,u;if(n&&typeof n.word=="string")return n.word;if(a){let{range:c}=a;if(u=a.newText,c&&c.start.line==c.end.line){let{line:f,col:p,colnr:d}=e,h=Mf(f,p);if(c.start.character>h)u=f.slice(h,c.start.character)+u;else{let m=f.slice(c.start.character,h);m.length&&u.startsWith(m)&&(u=u.slice(m.length))}if(h=Mf(f,d-1),c.end.character>h){let m=f.slice(h,c.end.character);u.endsWith(m)&&(u=u.slice(0,-m.length))}}}else u=s;if(o==L4.InsertTextFormat.Snippet&&u&&u.includes("$")){let f=new Ho().text(u);l=f?N4(f,t):i}else l=N4(u,t)||i;return l||""}function $4(r,e,t=""){return e.get(r)||t}function N4(r,e){if(!r)return"";for(let t=0;t{e.affectsConfiguration("suggest")&&this.loadCompleteConfig()},this)}get nvim(){return b.nvim}get detailField(){let{detailField:e,floatEnable:t}=this.completeConfig;return e=="preview"&&(!t||!b.floatSupported)?"menu":"preview"}loadCompleteConfig(){let e=b.getConfiguration("suggest"),t=e.get("completionItemKindLabels",{});this.completionItemKindMap=new Map([[ce.CompletionItemKind.Text,t.text||"v"],[ce.CompletionItemKind.Method,t.method||"f"],[ce.CompletionItemKind.Function,t.function||"f"],[ce.CompletionItemKind.Constructor,typeof t.constructor=="function"?"f":t["constructor"]],[ce.CompletionItemKind.Field,t.field||"m"],[ce.CompletionItemKind.Variable,t.variable||"v"],[ce.CompletionItemKind.Class,t.class||"C"],[ce.CompletionItemKind.Interface,t.interface||"I"],[ce.CompletionItemKind.Module,t.module||"M"],[ce.CompletionItemKind.Property,t.property||"m"],[ce.CompletionItemKind.Unit,t.unit||"U"],[ce.CompletionItemKind.Value,t.value||"v"],[ce.CompletionItemKind.Enum,t.enum||"E"],[ce.CompletionItemKind.Keyword,t.keyword||"k"],[ce.CompletionItemKind.Snippet,t.snippet||"S"],[ce.CompletionItemKind.Color,t.color||"v"],[ce.CompletionItemKind.File,t.file||"F"],[ce.CompletionItemKind.Reference,t.reference||"r"],[ce.CompletionItemKind.Folder,t.folder||"F"],[ce.CompletionItemKind.EnumMember,t.enumMember||"m"],[ce.CompletionItemKind.Constant,t.constant||"v"],[ce.CompletionItemKind.Struct,t.struct||"S"],[ce.CompletionItemKind.Event,t.event||"E"],[ce.CompletionItemKind.Operator,t.operator||"O"],[ce.CompletionItemKind.TypeParameter,t.typeParameter||"T"]]),this.completeConfig={defaultKindText:t.default||"",priority:e.get("languageSourcePriority",99),echodocSupport:e.get("echodocSupport",!1),detailField:e.get("detailField","preview"),detailMaxLength:e.get("detailMaxLength",100),floatEnable:e.get("floatEnable",!0),invalidInsertCharacters:e.get("invalidInsertCharacters",["(","<","{","[","\r",` +`])}}hasFormatProvider(e){return!!(this.formatManager.hasProvider(e)||this.formatRangeManager.hasProvider(e))}registerOnTypeFormattingEditProvider(e,t,i){return this.onTypeFormatManager.register(e,t,i)}registerCompletionItemProvider(e,t,i,n,o=[],s,a){i=typeof i=="string"?[i]:i;let l=this.createCompleteSource(e,t,n,i,o,a||[],s);return Ze.addSource(l),mv.debug("created service source",e),{dispose:()=>{Ze.removeSource(l)}}}registerCodeActionProvider(e,t,i,n){return this.codeActionManager.register(e,t,i,n)}registerHoverProvider(e,t){return this.hoverManager.register(e,t)}registerSelectionRangeProvider(e,t){return this.selectionRangeManager.register(e,t)}registerSignatureHelpProvider(e,t,i){return this.signatureManager.register(e,t,i)}registerDocumentSymbolProvider(e,t){return this.documentSymbolManager.register(e,t)}registerFoldingRangeProvider(e,t){return this.foldingRangeManager.register(e,t)}registerDocumentHighlightProvider(e,t){return this.documentHighlightManager.register(e,t)}registerCodeLensProvider(e,t){return this.codeLensManager.register(e,t)}registerDocumentLinkProvider(e,t){return this.documentLinkManager.register(e,t)}registerDocumentColorProvider(e,t){return this.documentColorManager.register(e,t)}registerDefinitionProvider(e,t){return this.definitionManager.register(e,t)}registerDeclarationProvider(e,t){return this.declarationManager.register(e,t)}registerTypeDefinitionProvider(e,t){return this.typeDefinitionManager.register(e,t)}registerImplementationProvider(e,t){return this.implementationManager.register(e,t)}registerReferencesProvider(e,t){return this.referenceManager.register(e,t)}registerRenameProvider(e,t){return this.renameManager.register(e,t)}registerWorkspaceSymbolProvider(e){return arguments.length>1&&typeof arguments[1].provideWorkspaceSymbols=="function"&&(e=arguments[1]),this.workspaceSymbolsManager.register(e)}registerDocumentFormatProvider(e,t,i=0){return this.formatManager.register(e,t,i)}registerDocumentRangeFormatProvider(e,t,i=0){return this.formatRangeManager.register(e,t,i)}shouldTriggerSignatureHelp(e,t){return this.signatureManager.shouldTrigger(e,t)}async getHover(e,t,i){return await this.hoverManager.provideHover(e,t,i)}async getSignatureHelp(e,t,i,n){return await this.signatureManager.provideSignatureHelp(e,t,i,n)}async getDefinition(e,t,i){return this.definitionManager.hasProvider(e)?await this.definitionManager.provideDefinition(e,t,i):null}async getDeclaration(e,t,i){return this.declarationManager.hasProvider(e)?await this.declarationManager.provideDeclaration(e,t,i):null}async getTypeDefinition(e,t,i){return this.typeDefinitionManager.hasProvider(e)?await this.typeDefinitionManager.provideTypeDefinition(e,t,i):null}async getImplementation(e,t,i){return this.implementationManager.hasProvider(e)?await this.implementationManager.provideReferences(e,t,i):null}async getReferences(e,t,i,n){return this.referenceManager.hasProvider(e)?await this.referenceManager.provideReferences(e,i,t,n):null}async getDocumentSymbol(e,t){return await this.documentSymbolManager.provideDocumentSymbols(e,t)}async getSelectionRanges(e,t,i){return await this.selectionRangeManager.provideSelectionRanges(e,t,i)}async getWorkspaceSymbols(e,t){return e=e||"",await this.workspaceSymbolsManager.provideWorkspaceSymbols(e,t)}async resolveWorkspaceSymbol(e,t){return await this.workspaceSymbolsManager.resolveWorkspaceSymbol(e,t)}async prepareRename(e,t,i){return await this.renameManager.prepareRename(e,t,i)}async provideRenameEdits(e,t,i,n){return await this.renameManager.provideRenameEdits(e,t,i,n)}async provideDocumentFormattingEdits(e,t,i){if(!this.formatManager.hasProvider(e)){if(!this.formatRangeManager.hasProvider(e))return null;let o=e.positionAt(e.getText().length),s=ce.Range.create(ce.Position.create(0,0),o);return await this.provideDocumentRangeFormattingEdits(e,s,t,i)}return await this.formatManager.provideDocumentFormattingEdits(e,t,i)}async provideDocumentRangeFormattingEdits(e,t,i,n){return this.formatRangeManager.hasProvider(e)?await this.formatRangeManager.provideDocumentRangeFormattingEdits(e,t,i,n):null}async getCodeActions(e,t,i,n){return await this.codeActionManager.provideCodeActions(e,t,i,n)}async getDocumentHighLight(e,t,i){return await this.documentHighlightManager.provideDocumentHighlights(e,t,i)}async getDocumentLinks(e,t){return this.documentLinkManager.hasProvider(e)?await this.documentLinkManager.provideDocumentLinks(e,t)||[]:null}async resolveDocumentLink(e){return await this.documentLinkManager.resolveDocumentLink(e,this.token)}async provideDocumentColors(e,t){return await this.documentColorManager.provideDocumentColors(e,t)}async provideFoldingRanges(e,t,i){return this.foldingRangeManager.hasProvider(e)?await this.foldingRangeManager.provideFoldingRanges(e,t,i):null}async provideColorPresentations(e,t,i){return await this.documentColorManager.provideColorPresentations(e,t,i)}async getCodeLens(e,t){return await this.codeLensManager.provideCodeLenses(e,t)}async resolveCodeLens(e,t){return await this.codeLensManager.resolveCodeLens(e,t)}async provideDocumentOnTypeEdits(e,t,i,n){return this.onTypeFormatManager.onCharacterType(e,t,i,n)}hasOnTypeProvider(e,t){return this.onTypeFormatManager.getProvider(t,e)!=null}hasProvider(e,t){switch(e){case"rename":return this.renameManager.hasProvider(t);case"onTypeEdit":return this.onTypeFormatManager.hasProvider(t);case"documentLink":return this.documentLinkManager.hasProvider(t);case"documentColor":return this.documentColorManager.hasProvider(t);case"foldingRange":return this.foldingRangeManager.hasProvider(t);case"format":return this.formatManager.hasProvider(t)||this.formatRangeManager.hasProvider(t);case"codeAction":return this.codeActionManager.hasProvider(t);case"workspaceSymbols":return this.workspaceSymbolsManager.hasProvider();case"formatRange":return this.formatRangeManager.hasProvider(t);case"hover":return this.hoverManager.hasProvider(t);case"signature":return this.signatureManager.hasProvider(t);case"documentSymbol":return this.documentSymbolManager.hasProvider(t);case"documentHighlight":return this.documentHighlightManager.hasProvider(t);case"definition":return this.definitionManager.hasProvider(t);case"declaration":return this.declarationManager.hasProvider(t);case"typeDefinition":return this.typeDefinitionManager.hasProvider(t);case"reference":return this.referenceManager.hasProvider(t);case"implementation":return this.implementationManager.hasProvider(t);case"codeLens":return this.codeLensManager.hasProvider(t);case"selectionRange":return this.selectionRangeManager.hasProvider(t);default:throw new Error(`${e} not supported.`)}}dispose(){}createDiagnosticCollection(e){return St.create(e)}createCompleteSource(e,t,i,n,o,s,a){let l=[],u=typeof i.resolveCompletionItem=="function";a=a==null?this.completeConfig.priority:a;let c=new Set,f={name:e,priority:a,shortcut:t,enable:!0,sourceType:Yr.Service,filetypes:n,triggerCharacters:o||[],toggle:()=>{f.enable=!f.enable},doComplete:async(p,d)=>{let{triggerCharacter:h,bufnr:m}=p;c=new Set;let y=o&&o.includes(h),v=ce.CompletionTriggerKind.Invoked;if(p.triggerForInComplete?v=ce.CompletionTriggerKind.TriggerForIncompleteCompletions:y&&(v=ce.CompletionTriggerKind.TriggerCharacter),d.isCancellationRequested)return null;let x=M4(p),w={triggerKind:v,option:p};y&&(w.triggerCharacter=h);let E;try{let I=b.getDocument(m);E=await Promise.resolve(i.provideCompletionItems(I.textDocument,x,d,w))}catch(I){return mv.error(`Complete "${e}" error:`,I),null}if(!E||d.isCancellationRequested||(l=Array.isArray(E)?E:E.items,!l||l.length==0))return null;let P=this.getStartColumn(p.line,l),k=Object.assign({},p),_;P!=null&&(P{let R=this.convertVimCompleteItem(I,t,k,_);return R.index=L,R});return{startcol:P,isIncomplete:!!E.isIncomplete,items:O}},onCompleteResolve:async(p,d)=>{let h=l[p.index];if(!!h){if(u&&!c.has(p.index)){let m=await Promise.resolve(i.resolveCompletionItem(h,d));if(d.isCancellationRequested)return;c.add(p.index),m&&Object.assign(h,m)}if(p.documentation==null){let{documentation:m,detail:y}=h;if(!m&&!y)return;let v=[];if(y&&!p.detailShown&&y!=p.word&&(y=y.replace(/\n\s*/g," "),y.length)){let x=/^[\w-\s.,\t]+$/.test(y),w=x?"txt":await b.nvim.eval("&filetype");v.push({filetype:x?"txt":w,content:y})}m&&(typeof m=="string"?v.push({filetype:"markdown",content:m}):m.value&&v.push({filetype:m.kind=="markdown"?"markdown":"txt",content:m.value})),p.documentation=v}}},onCompleteDone:async(p,d)=>{let h=l[p.index];if(!h)return;let m=d.linenr-1;h.insertText!=null&&!h.textEdit&&(h.textEdit={range:ce.Range.create(m,d.col,m,d.colnr-1),newText:h.insertText}),p.line&&Object.assign(d,{line:p.line});try{let y=await this.applyTextEdit(h,d),{additionalTextEdits:v}=h;if(v&&h.textEdit){let x=h.textEdit.range;v=v.filter(w=>Mm(x,w.range)?(mv.error("Filtered overlap additionalTextEdit:",w),!1):!0)}await this.applyAdditionalEdits(v,d.bufnr,y),y&&await Ft.selectCurrentPlaceholder(),h.command&&me.has(h.command.command)&&me.execute(h.command)}catch(y){mv.error("Error on CompleteDone:",y)}},shouldCommit:(p,d)=>{let h=l[p.index];return h?(h.commitCharacters||s).includes(d):!1}};return f}get token(){return this.cancelTokenSource=new ce.CancellationTokenSource,this.cancelTokenSource.token}async applyTextEdit(e,t){let{nvim:i}=this,{textEdit:n}=e;if(!n)return!1;let{line:o,bufnr:s,linenr:a}=t,l=b.getDocument(s);if(!l)return!1;let{range:u,newText:c}=n,f=e.insertTextFormat===ce.InsertTextFormat.Snippet,p=o.substr(0,u.start.character),d=o.substr(u.end.character);if(f){let y=l.getline(a-1).length-d.length,v=ce.Range.create(a-1,u.start.character,a-1,y);return await Ft.insertSnippet(c,!1,v)}let h=`${p}${c}${d}`.split(/\r?\n/);if(h.length==1)await i.call("coc#util#setline",[a,h[0]]),await C.moveTo(ce.Position.create(a-1,(p+c).length));else{await i.createBuffer(s).setLines(h,{start:a-1,end:a,strictIndexing:!1});let y=a-1+h.length-1,v=h[h.length-1].length-d.length;await C.moveTo({line:y,character:v})}return!1}async applyAdditionalEdits(e,t,i){if(!e||e.length==0)return;let n=b.getDocument(t);if(!n)return;await n.patchChange(!0);let o=null,s=await C.getCursorPosition();i||(o=$l(s,e)),await n.applyEdits(e),o&&await C.moveTo(ce.Position.create(s.line+o.line,s.character+o.character))}getStartColumn(e,t){let i=t[0];if(!i.textEdit)return null;let{range:n,newText:o}=i.textEdit,{character:s}=n.start;if(o.length0,c=e.insertTextFormat===ce.InsertTextFormat.Snippet||u,f=e.label.trim(),p={word:q4(e,i,a),abbr:f,menu:`[${t}]`,kind:$4(e.kind,this.completionItemKindMap,this.completeConfig.defaultKindText),sortText:e.sortText||null,sourceScore:e.score||null,filterText:e.filterText||f,isSnippet:c,dup:e.data&&e.data.dup==0?0:1};if(n&&(p.filterText.startsWith(n)||(e.textEdit&&e.textEdit.newText.startsWith(n)?p.filterText=e.textEdit.newText.split(/\r?\n/)[0]:p.filterText=`${n}${p.filterText}`),!e.textEdit&&!p.word.startsWith(n)&&(p.word=`${n}${p.word}`)),e&&e.detail&&l!="preview"){let h=e.detail.replace(/\n\s*/g," ");ue(h)=2&&e.kind<=4){let h=[e.detail||"",p.abbr,p.word];for(let m of h)if(m.includes("(")){p.signature=m;break}}return e.preselect&&(p.preselect=!0),((d=e.data)==null?void 0:d.optional)&&(p.abbr=p.abbr+"?"),p}},U=new B4;var $E=class{constructor(e=-1){this.srcId=e;this.lines=[];this.highlights=[]}addLine(e,t){if(e.includes(` +`)){for(let i of e.split(/\r?\n/))this.addLine(i,t);return}if(t&&this.highlights.push({line:this.lines.length,colStart:e.match(/^\s*/)[0].length,colEnd:ue(e),hlGroup:t}),e.includes("")){let i=Nl(e);for(let n of i.highlights){let{span:o,hlGroup:s}=n;o[0]!=o[1]&&this.highlights.push({line:this.lines.length,colStart:o[0],colEnd:o[1],hlGroup:s})}this.lines.push(i.line)}else this.lines.push(e)}addLines(e){this.lines.push(...e)}addText(e,t){let{lines:i}=this,n=i[i.length-1]||"";if(t){let o=ue(n);this.highlights.push({line:i.length?i.length-1:0,colStart:o,colEnd:o+ue(e),hlGroup:t})}i.length?i[i.length-1]=`${n}${e}`:i.push(e)}get length(){return this.lines.length}getline(e){return this.lines[e]||""}render(e,t=0,i=-1){e.setLines(this.lines,{start:t,end:i,strictIndexing:!1},!0);for(let n of this.highlights)e.addHighlight({hlGroup:n.hlGroup,colStart:n.colStart,colEnd:n.colEnd==null?-1:n.colEnd,line:t+n.line,srcId:this.srcId}).logError()}},ss=$E;var BH=S(require("events")),jH=S(require("fs")),UH=S(require("net")),Ru=S(W());var Sa=S(require("child_process")),qH=S(require("fs")),nC=S(require("path")),Et=S(W());var jp=S(require("child_process")),gv=S(require("path")),j4=S(require("fs"));var oye=process.platform==="win32",sye=process.platform==="darwin",aye=process.platform==="linux",lye=gv.dirname(__dirname);function U4(r,e){if(!r.killed)if(oye)try{let t={stdio:["pipe","pipe","ignore"]};return e&&(t.cwd=e),jp.execFileSync("taskkill",["/T","/F","/PID",r.pid.toString()],t),!0}catch(t){return!1}else if(aye||sye)try{let t=gv.join(lye,"bin/terminateProcess.sh");return j4.default.existsSync(t)?!jp.spawnSync(t,[r.pid.toString()]).error:(console.error(`"${t}" not found`),!1)}catch(t){return!1}else return r.kill("SIGKILL"),!0}var WE=S(require("path")),D=S(W());var W4=S(W());"use strict";var g$e=j()("language-client-progressPart"),Up=class{constructor(e,t,i){this.client=e;this.token=t;this.disposables=[];this._cancelled=!1;this.statusBarItem=C.createStatusBarItem(99,{progress:!0}),this.disposables.push(e.onProgress(W4.WorkDoneProgress.type,this.token,n=>{switch(n.kind){case"begin":this.begin(n);break;case"report":this.report(n);break;case"end":this.done(n.message),i&&i(this);break}}))}begin(e){typeof this.title!="string"&&(this.title=e.title,this.report(e))}report(e){let t=this.statusBarItem,i=[];this.title&&i.push(this.title),typeof e.percentage=="number"&&i.push(e.percentage.toFixed(0)+"%"),e.message&&i.push(e.message),t.text=i.join(" "),t.show()}cancel(){this._cancelled||(this._cancelled=!0,z(this.disposables))}done(e){if(this._cancelled)return;let t=this.statusBarItem;t.text=`${this.title} ${e||"finished"}`,setTimeout(()=>{t.dispose()},300),this.cancel()}};var BE=class{constructor(e){this.defaultDelay=e;this.timeout=null,this.completionPromise=null,this.doResolve=null,this.task=null}trigger(e,t=this.defaultDelay){return this.task=e,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise((i,n)=>{this.doResolve=i,this.doReject=n}).then(()=>{this.completionPromise=null,this.doResolve=null;let i=this.task;return this.task=null,i()})),this.timeout=setTimeout(()=>{this.timeout=null,this.doResolve(null)},t),this.completionPromise}isTriggered(){return this.timeout!==null}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject(new Error("Canceled")),this.completionPromise=null)}cancelTimeout(){this.timeout!==null&&(clearTimeout(this.timeout),this.timeout=null)}dispose(){this.cancelTimeout()}};function H4(r){let e=r.map(t=>typeof t=="string"?t:t.language);return e=e.filter(t=>t!=null),e.length==0?null:e}function z4(r){return{uri:r.uri,languageId:r.languageId,version:r.version,text:r.getText()}}function G4(r){return{textDocument:{uri:r.uri}}}function V4(r){return{textDocument:{uri:r.uri,version:r.version},contentChanges:[{text:r.getText()}]}}function jE(r){return{textDocument:vv(r.document),reason:r.reason}}function vv(r){return{uri:r.uri,version:r.version}}function K4(r,e){let t={textDocument:vv(r)};return e&&(t.text=r.getText()),t}function Wp(r){return r.toString()}function J4(r,e,t){return{textDocument:{uri:r.uri},position:e,context:xa(t,["option"])}}function En(r,e){return{textDocument:{uri:r.uri},position:e}}function Y4(r,e,t){return{textDocument:UE(r),position:e,context:t}}function UE(r){return{uri:r.uri}}function X4(r,e,t){return{textDocument:{uri:r.uri},position:e,context:{includeDeclaration:t.includeDeclaration}}}function Z4(r){return{textDocument:{uri:r.uri}}}function Q4(r){return{textDocument:{uri:r.uri}}}function $e(){return he()}var as=j()("language-client-client"),eH=class{error(e){as.error(e)}warn(e){as.warn(e)}info(e){as.info(e)}log(e){as.log(e)}},tH=class{error(e){}warn(e){}info(e){}log(e){}};function uye(r,e,t,i){let n=new eH,o=D.createProtocolConnection(r,e,n);return o.onError(a=>{t(a[0],a[1],a[2])}),o.onClose(i),{listen:()=>o.listen(),sendRequest:(a,...l)=>o.sendRequest(bt(a)?a:a.method,...l),onRequest:(a,l)=>o.onRequest(bt(a)?a:a.method,l),sendNotification:(a,l)=>o.sendNotification(bt(a)?a:a.method,l),onNotification:(a,l)=>o.onNotification(bt(a)?a:a.method,l),onProgress:o.onProgress,sendProgress:o.sendProgress,trace:(a,l,u)=>{let c={sendNotification:!1,traceFormat:D.TraceFormat.Text};u===void 0?o.trace(a,l,c):(Tl(u),o.trace(a,l,u))},initialize:a=>o.sendRequest(D.InitializeRequest.type,a),shutdown:()=>o.sendRequest(D.ShutdownRequest.type,void 0),exit:()=>o.sendNotification(D.ExitNotification.type),onLogMessage:a=>o.onNotification(D.LogMessageNotification.type,a),onShowMessage:a=>o.onNotification(D.ShowMessageNotification.type,a),onTelemetry:a=>o.onNotification(D.TelemetryEventNotification.type,a),didChangeConfiguration:a=>o.sendNotification(D.DidChangeConfigurationNotification.type,a),didChangeWatchedFiles:a=>o.sendNotification(D.DidChangeWatchedFilesNotification.type,a),didOpenTextDocument:a=>o.sendNotification(D.DidOpenTextDocumentNotification.type,a),didChangeTextDocument:a=>o.sendNotification(D.DidChangeTextDocumentNotification.type,a),didCloseTextDocument:a=>o.sendNotification(D.DidCloseTextDocumentNotification.type,a),didSaveTextDocument:a=>o.sendNotification(D.DidSaveTextDocumentNotification.type,a),onDiagnostics:a=>o.onNotification(D.PublishDiagnosticsNotification.type,a),dispose:()=>o.dispose()}}var Tu;(function(r){r[r.Continue=1]="Continue",r[r.Shutdown=2]="Shutdown"})(Tu||(Tu={}));var ro;(function(r){r[r.DoNotRestart=1]="DoNotRestart",r[r.Restart=2]="Restart"})(ro||(ro={}));var HE=class{constructor(e){this.name=e;this.restarts=[]}error(e,t,i){return i&&i<=3?1:2}closed(){return this.restarts.push(Date.now()),this.restarts.length<5?2:this.restarts[this.restarts.length-1]-this.restarts[0]<=3*60*1e3?(C.showMessage(`The "${this.name}" server crashed 5 times in the last 3 minutes. The server will not be restarted.`,"error"),1):(this.restarts.shift(),2)}},ii;(function(r){r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Never=4]="Never"})(ii||(ii={}));var ni;(function(r){r[r.Stopped=1]="Stopped",r[r.Running=2]="Running",r[r.Starting=3]="Starting"})(ni||(ni={}));var be;(function(r){r[r.Initial=0]="Initial",r[r.Starting=1]="Starting",r[r.StartFailed=2]="StartFailed",r[r.Running=3]="Running",r[r.Stopping=4]="Stopping",r[r.Stopped=5]="Stopped"})(be||(be={}));var rH=[D.SymbolKind.File,D.SymbolKind.Module,D.SymbolKind.Namespace,D.SymbolKind.Package,D.SymbolKind.Class,D.SymbolKind.Method,D.SymbolKind.Property,D.SymbolKind.Field,D.SymbolKind.Constructor,D.SymbolKind.Enum,D.SymbolKind.Interface,D.SymbolKind.Function,D.SymbolKind.Variable,D.SymbolKind.Constant,D.SymbolKind.String,D.SymbolKind.Number,D.SymbolKind.Boolean,D.SymbolKind.Array,D.SymbolKind.Object,D.SymbolKind.Key,D.SymbolKind.Null,D.SymbolKind.EnumMember,D.SymbolKind.Struct,D.SymbolKind.Event,D.SymbolKind.Operator,D.SymbolKind.TypeParameter],cye=[D.CompletionItemKind.Text,D.CompletionItemKind.Method,D.CompletionItemKind.Function,D.CompletionItemKind.Constructor,D.CompletionItemKind.Field,D.CompletionItemKind.Variable,D.CompletionItemKind.Class,D.CompletionItemKind.Interface,D.CompletionItemKind.Module,D.CompletionItemKind.Property,D.CompletionItemKind.Unit,D.CompletionItemKind.Value,D.CompletionItemKind.Enum,D.CompletionItemKind.Keyword,D.CompletionItemKind.Snippet,D.CompletionItemKind.Color,D.CompletionItemKind.File,D.CompletionItemKind.Reference,D.CompletionItemKind.Folder,D.CompletionItemKind.EnumMember,D.CompletionItemKind.Constant,D.CompletionItemKind.Struct,D.CompletionItemKind.Event,D.CompletionItemKind.Operator,D.CompletionItemKind.TypeParameter],iH=[D.SymbolTag.Deprecated];function re(r,e){return r[e]==null&&(r[e]={}),r[e]}var zE;(function(e){function r(t){let i=t;return i&&Lo(i.register)&&Lo(i.unregister)&&Lo(i.dispose)&&i.messages!==void 0}e.is=r})(zE||(zE={}));var Cn=class{constructor(e,t,i,n,o,s){this._client=e;this._event=t;this._type=i;this._middleware=n;this._createParams=o;this._selectorFilter=s;this._selectors=new Map}static textDocumentFilter(e,t){for(let i of e)if(b.match(i,t)>0)return!0;return!1}register(e,t){!t.registerOptions.documentSelector||(this._listener||(this._listener=this._event(this.callback,this)),this._selectors.set(t.id,t.registerOptions.documentSelector))}callback(e){(!this._selectorFilter||this._selectorFilter(this._selectors.values(),e))&&(this._middleware?this._middleware(e,t=>this._client.sendNotification(this._type,this._createParams(t))):this._client.sendNotification(this._type,this._createParams(e)),this.notificationSent(e))}notificationSent(e){}unregister(e){this._selectors.delete(e),this._selectors.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._selectors.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}getProvider(e){for(let t of this._selectors.values())if(b.match(t,e))return{send:i=>{this.callback(i)}};throw new Error("No provider available for the given text document")}},nH=class extends Cn{constructor(e,t){super(e,b.onDidOpenTextDocument,D.DidOpenTextDocumentNotification.type,e.clientOptions.middleware.didOpen,i=>({textDocument:z4(i)}),Cn.textDocumentFilter);this._syncedDocuments=t}get messages(){return D.DidOpenTextDocumentNotification.type}fillClientCapabilities(e){re(re(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.openClose&&this.register(this.messages,{id:$e(),registerOptions:{documentSelector:t}})}register(e,t){if(super.register(e,t),!t.registerOptions.documentSelector)return;let i=t.registerOptions.documentSelector;b.textDocuments.forEach(n=>{let o=n.uri.toString();if(!this._syncedDocuments.has(o)&&b.match(i,n)>0){let s=this._client.clientOptions.middleware,a=l=>{this._client.sendNotification(this._type,this._createParams(l))};s.didOpen?s.didOpen(n,a):a(n),this._syncedDocuments.set(o,n)}})}notificationSent(e){super.notificationSent(e),this._syncedDocuments.set(e.uri.toString(),e)}},oH=class extends Cn{constructor(e,t){super(e,b.onDidCloseTextDocument,D.DidCloseTextDocumentNotification.type,e.clientOptions.middleware.didClose,i=>G4(i),Cn.textDocumentFilter);this._syncedDocuments=t}get messages(){return D.DidCloseTextDocumentNotification.type}fillClientCapabilities(e){re(re(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.openClose&&this.register(this.messages,{id:$e(),registerOptions:{documentSelector:t}})}notificationSent(e){super.notificationSent(e),this._syncedDocuments.delete(e.uri.toString())}unregister(e){let t=this._selectors.get(e);super.unregister(e);let i=this._selectors.values();this._syncedDocuments.forEach(n=>{if(b.match(t,n)>0&&!this._selectorFilter(i,n)){let o=this._client.clientOptions.middleware,s=a=>{this._client.sendNotification(this._type,this._createParams(a))};this._syncedDocuments.delete(n.uri.toString()),o.didClose?o.didClose(n,s):s(n)}})}},sH=class{constructor(e){this._client=e;this._changeData=new Map}get messages(){return D.DidChangeTextDocumentNotification.type}fillClientCapabilities(e){re(re(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.change!==void 0&&i.change!==D.TextDocumentSyncKind.None&&this.register(this.messages,{id:$e(),registerOptions:Object.assign({},{documentSelector:t},{syncKind:i.change})})}register(e,t){!t.registerOptions.documentSelector||(this._listener||(this._listener=b.onDidChangeTextDocument(this.callback,this)),this._changeData.set(t.id,{documentSelector:t.registerOptions.documentSelector,syncKind:t.registerOptions.syncKind}))}callback(e){if(e.contentChanges.length===0)return;let t=b.getDocument(e.textDocument.uri);if(!t)return;let{textDocument:i}=t;for(let n of this._changeData.values())if(b.match(n.documentSelector,i)>0){let o=this._client.clientOptions.middleware;if(n.syncKind===D.TextDocumentSyncKind.Incremental)o.didChange?o.didChange(e,()=>this._client.sendNotification(D.DidChangeTextDocumentNotification.type,xa(e,["bufnr","original"]))):this._client.sendNotification(D.DidChangeTextDocumentNotification.type,xa(e,["bufnr","original"]));else if(n.syncKind===D.TextDocumentSyncKind.Full){let s=a=>{let{textDocument:l}=b.getDocument(a.textDocument.uri);this._client.sendNotification(D.DidChangeTextDocumentNotification.type,V4(l))};o.didChange?o.didChange(e,s):s(e)}}}unregister(e){this._changeData.delete(e),this._changeData.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._changeData.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}getProvider(e){for(let t of this._changeData.values())if(b.match(t.documentSelector,e))return{send:i=>{this.callback(i)}};throw new Error("No provider available for the given text document")}},aH=class extends Cn{constructor(e){super(e,b.onWillSaveTextDocument,D.WillSaveTextDocumentNotification.type,e.clientOptions.middleware.willSave,t=>jE(t),(t,i)=>Cn.textDocumentFilter(t,i.document))}get messages(){return D.WillSaveTextDocumentNotification.type}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"synchronization");t.willSave=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.willSave&&this.register(this.messages,{id:$e(),registerOptions:{documentSelector:t}})}},lH=class{constructor(e){this._client=e;this._selectors=new Map}get messages(){return D.WillSaveTextDocumentWaitUntilRequest.type}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"synchronization");t.willSaveWaitUntil=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.willSaveWaitUntil&&this.register(this.messages,{id:$e(),registerOptions:{documentSelector:t}})}register(e,t){!t.registerOptions.documentSelector||(this._listener||(this._listener=b.onWillSaveTextDocument(this.callback,this)),this._selectors.set(t.id,t.registerOptions.documentSelector))}callback(e){if(Cn.textDocumentFilter(this._selectors.values(),e.document)){let t=this._client.clientOptions.middleware,i=n=>this._client.sendRequest(D.WillSaveTextDocumentWaitUntilRequest.type,jE(n)).then(o=>o||[],o=>(C.showMessage(`Error on willSaveWaitUntil: ${o}`,"error"),as.error(o),[]));e.waitUntil(t.willSaveWaitUntil?t.willSaveWaitUntil(e,i):i(e))}}unregister(e){this._selectors.delete(e),this._selectors.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._selectors.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}},uH=class extends Cn{constructor(e){super(e,b.onDidSaveTextDocument,D.DidSaveTextDocumentNotification.type,e.clientOptions.middleware.didSave,t=>K4(t,this._includeText),Cn.textDocumentFilter)}get messages(){return D.DidSaveTextDocumentNotification.type}fillClientCapabilities(e){re(re(e,"textDocument"),"synchronization").didSave=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.save&&this.register(this.messages,{id:$e(),registerOptions:Object.assign({},{documentSelector:t},{includeText:!!i.save.includeText})})}register(e,t){this._includeText=!!t.registerOptions.includeText,super.register(e,t)}},cH=class{constructor(e,t){this._notifyFileEvent=t;this._watchers=new Map}get messages(){return D.DidChangeWatchedFilesNotification.type}fillClientCapabilities(e){re(re(e,"workspace"),"didChangeWatchedFiles").dynamicRegistration=!0}initialize(e,t){}register(e,t){if(!Array.isArray(t.registerOptions.watchers))return;let i=[];for(let n of t.registerOptions.watchers){if(!bt(n.globPattern))continue;let o=!0,s=!0,a=!0;n.kind!=null&&(o=(n.kind&D.WatchKind.Create)!=0,s=(n.kind&D.WatchKind.Change)!=0,a=(n.kind&D.WatchKind.Delete)!=0);let l=b.createFileSystemWatcher(n.globPattern,!o,!s,!a);this.hookListeners(l,o,s,a,i),i.push(l)}this._watchers.set(t.id,i)}registerRaw(e,t){let i=[];for(let n of t)i.push(n),this.hookListeners(n,!0,!0,!0,i);this._watchers.set(e,i)}hookListeners(e,t,i,n,o){t&&e.onDidCreate(s=>this._notifyFileEvent({uri:Wp(s),type:D.FileChangeType.Created}),null,o),i&&e.onDidChange(s=>this._notifyFileEvent({uri:Wp(s),type:D.FileChangeType.Changed}),null,o),n&&e.onDidDelete(s=>this._notifyFileEvent({uri:Wp(s),type:D.FileChangeType.Deleted}),null,o)}unregister(e){let t=this._watchers.get(e);if(t)for(let i of t)i.dispose()}dispose(){this._watchers.forEach(e=>{for(let t of e)t.dispose()}),this._watchers.clear()}},Ge=class{constructor(e,t){this._client=e;this._message=t;this._registrations=new Map}get messages(){return this._message}register(e,t){if(e.method!==this.messages.method)throw new Error(`Register called on wrong feature. Requested ${e.method} but reached feature ${this.messages.method}`);if(!t.registerOptions.documentSelector)return;let i=this.registerLanguageProvider(t.registerOptions);this._registrations.set(t.id,{disposable:i[0],data:t,provider:i[1]})}unregister(e){let t=this._registrations.get(e);t&&t.disposable.dispose()}dispose(){this._registrations.forEach(e=>{e.disposable.dispose()}),this._registrations.clear()}getRegistration(e,t){if(t){if(D.TextDocumentRegistrationOptions.is(t)){let i=D.StaticRegistrationOptions.hasId(t)?t.id:$e(),n=t.documentSelector||e;if(n)return[i,Object.assign({},t,{documentSelector:n})]}else if(Tl(t)&&t===!0||D.WorkDoneProgressOptions.is(t)){if(!e)return[void 0,void 0];let i=Tl(t)&&t===!0?{documentSelector:e}:Object.assign({},t,{documentSelector:e});return[$e(),i]}}else return[void 0,void 0];return[void 0,void 0]}getRegistrationOptions(e,t){if(!(!e||!t))return Tl(t)&&t===!0?{documentSelector:e}:Object.assign({},t,{documentSelector:e})}getProvider(e){for(let t of this._registrations.values()){let i=t.data.registerOptions.documentSelector;if(i!==null&&b.match(i,e)>0)return t.provider}throw new Error(`The feature has no registration for the provided text document ${e.uri.toString()}`)}},fH=class{constructor(e,t){this._client=e;this._message=t;this._registrations=new Map}get messages(){return this._message}register(e,t){if(e.method!==this.messages.method)throw new Error(`Register called on wrong feature. Requested ${e.method} but reached feature ${this.messages.method}`);let i=this.registerLanguageProvider(t.registerOptions);this._registrations.set(t.id,i)}unregister(e){let t=this._registrations.get(e);t&&t.dispose()}dispose(){this._registrations.forEach(e=>{e.dispose()}),this._registrations.clear()}},pH=class extends Ge{constructor(e){super(e,D.CompletionRequest.type)}fillClientCapabilities(e){let t=this._client.clientOptions.disableSnippetCompletion!==!0,i=re(re(e,"textDocument"),"completion");i.dynamicRegistration=!0,i.contextSupport=!0,i.completionItem={snippetSupport:t,commitCharactersSupport:!0,documentationFormat:this._client.supporedMarkupKind,deprecatedSupport:!0,preselectSupport:!0,tagSupport:{valueSet:[D.CompletionItemTag.Deprecated]}},i.completionItemKind={valueSet:cye}}initialize(e,t){this.index=0;let i=this.getRegistrationOptions(t,e.completionProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t=e.triggerCharacters||[],i=e.allCommitCharacters||[],n=e.priority;this.index=this.index+1;let o={provideCompletionItems:(l,u,c,f)=>{let p=this._client,d=this._client.clientOptions.middleware,h=(m,y,v,x)=>p.sendRequest(D.CompletionRequest.type,J4(m,y,v),x).then(w=>w,w=>(p.logFailedRequest(D.CompletionRequest.type,w),Promise.resolve([])));return d.provideCompletionItem?d.provideCompletionItem(l,u,f,c,h):h(l,u,f,c)},resolveCompletionItem:e.resolveProvider?(l,u)=>{let c=this._client,f=this._client.clientOptions.middleware,p=(d,h)=>c.sendRequest(D.CompletionResolveRequest.type,d,h).then(m=>m,m=>(c.logFailedRequest(D.CompletionResolveRequest.type,m),Promise.resolve(d)));return f.resolveCompletionItem?f.resolveCompletionItem(l,u,p):p(l,u)}:void 0},s=H4(e.documentSelector);return[U.registerCompletionItemProvider(this._client.id+"-"+this.index,"LS",s,o,t,n,i),o]}},dH=class extends Ge{constructor(e){super(e,D.HoverRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"hover");t.dynamicRegistration=!0,t.contentFormat=this._client.supporedMarkupKind}initialize(e,t){let i=this.getRegistrationOptions(t,e.hoverProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideHover:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(D.HoverRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(D.HoverRequest.type,p),Promise.resolve(null))),l=s.clientOptions.middleware;return l.provideHover?l.provideHover(i,n,o,a):a(i,n,o)}};return[U.registerHoverProvider(e.documentSelector,t),t]}},hH=class extends Ge{constructor(e){super(e,D.SignatureHelpRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"signatureHelp");t.dynamicRegistration=!0,t.contextSupport=!0,t.signatureInformation={documentationFormat:this._client.supporedMarkupKind,activeParameterSupport:!0,parameterInformation:{labelOffsetSupport:!0}}}initialize(e,t){let i=this.getRegistrationOptions(t,e.signatureHelpProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideSignatureHelp:(o,s,a,l)=>{let u=this._client,c=(p,d,h,m)=>u.sendRequest(D.SignatureHelpRequest.type,Y4(p,d,h),m).then(y=>y,y=>(u.logFailedRequest(D.SignatureHelpRequest.type,y),Promise.resolve(null))),f=u.clientOptions.middleware;return f.provideSignatureHelp?f.provideSignatureHelp(o,s,l,a,c):c(o,s,l,a)}},i=e.triggerCharacters||[];return[U.registerSignatureHelpProvider(e.documentSelector,t,i),t]}},mH=class extends Ge{constructor(e){super(e,D.DefinitionRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"definition");t.dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.definitionProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDefinition:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(D.DefinitionRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(D.DefinitionRequest.type,p),Promise.resolve(null))),l=s.clientOptions.middleware;return l.provideDefinition?l.provideDefinition(i,n,o,a):a(i,n,o)}};return[U.registerDefinitionProvider(e.documentSelector,t),t]}},gH=class extends Ge{constructor(e){super(e,D.ReferencesRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"references").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.referencesProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideReferences:(i,n,o,s)=>{let a=this._client,l=(c,f,p,d)=>a.sendRequest(D.ReferencesRequest.type,X4(c,f,p),d).then(h=>h,h=>(a.logFailedRequest(D.ReferencesRequest.type,h),Promise.resolve([]))),u=a.clientOptions.middleware;return u.provideReferences?u.provideReferences(i,n,o,s,l):l(i,n,o,s)}};return[U.registerReferencesProvider(e.documentSelector,t),t]}},vH=class extends Ge{constructor(e){super(e,D.DocumentHighlightRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"documentHighlight").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentHighlightProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentHighlights:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(D.DocumentHighlightRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(D.DocumentHighlightRequest.type,p),Promise.resolve([]))),l=s.clientOptions.middleware;return l.provideDocumentHighlights?l.provideDocumentHighlights(i,n,o,a):a(i,n,o)}};return[U.registerDocumentHighlightProvider(e.documentSelector,t),t]}},yH=class extends Ge{constructor(e){super(e,D.DocumentSymbolRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"documentSymbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:rH},t.hierarchicalDocumentSymbolSupport=!0,t.tagSupport={valueSet:iH}}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentSymbolProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentSymbols:(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.DocumentSymbolRequest.type,Z4(l),u).then(c=>{if(c!==null){if(c.length===0)return[];{let f=c[0];return D.DocumentSymbol.is(f),c}}},c=>(o.logFailedRequest(D.DocumentSymbolRequest.type,c),Promise.resolve([]))),a=o.clientOptions.middleware;return a.provideDocumentSymbols?a.provideDocumentSymbols(i,n,s):s(i,n)}};return[U.registerDocumentSymbolProvider(e.documentSelector,t),t]}},bH=class extends fH{constructor(e){super(e,D.WorkspaceSymbolRequest.type)}fillClientCapabilities(e){let t=re(re(e,"workspace"),"symbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:rH},t.tagSupport={valueSet:iH}}initialize(e){!e.workspaceSymbolProvider||this.register(this.messages,{id:$e(),registerOptions:e.workspaceSymbolProvider===!0?{workDoneProgress:!1}:e.workspaceSymbolProvider})}registerLanguageProvider(e){let t={provideWorkspaceSymbols:(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.WorkspaceSymbolRequest.type,{query:l},u).then(c=>c,c=>(o.logFailedRequest(D.WorkspaceSymbolRequest.type,c),Promise.resolve([]))),a=o.clientOptions.middleware;return a.provideWorkspaceSymbols?a.provideWorkspaceSymbols(i,n,s):s(i,n)}};return U.registerWorkspaceSymbolProvider(t)}},wH=class extends Ge{constructor(e){super(e,D.CodeActionRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"codeAction");t.dynamicRegistration=!0,t.isPreferredSupport=!0,t.codeActionLiteralSupport={codeActionKind:{valueSet:[D.CodeActionKind.Empty,D.CodeActionKind.QuickFix,D.CodeActionKind.Refactor,D.CodeActionKind.RefactorExtract,D.CodeActionKind.RefactorInline,D.CodeActionKind.RefactorRewrite,D.CodeActionKind.Source,D.CodeActionKind.SourceOrganizeImports]}}}initialize(e,t){let i=this.getRegistrationOptions(t,e.codeActionProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideCodeActions:(i,n,o,s)=>{let a=this._client,l=(c,f,p,d)=>{let h={textDocument:{uri:c.uri},range:f,context:p};return a.sendRequest(D.CodeActionRequest.type,h,d).then(m=>{if(m!==null)return m},m=>(a.logFailedRequest(D.CodeActionRequest.type,m),Promise.resolve([])))},u=a.clientOptions.middleware;return u.provideCodeActions?u.provideCodeActions(i,n,o,s,l):l(i,n,o,s)}};return[U.registerCodeActionProvider(e.documentSelector,t,this._client.id,e.codeActionKinds),t]}},xH=class extends Ge{constructor(e){super(e,D.CodeLensRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"codeLens").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.codeLensProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideCodeLenses:(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.CodeLensRequest.type,Q4(l),u).then(c=>c,c=>(o.logFailedRequest(D.CodeLensRequest.type,c),Promise.resolve([]))),a=o.clientOptions.middleware;return a.provideCodeLenses?a.provideCodeLenses(i,n,s):s(i,n)},resolveCodeLens:e.resolveProvider?(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.CodeLensResolveRequest.type,l,u).then(c=>c,c=>(o.logFailedRequest(D.CodeLensResolveRequest.type,c),l)),a=o.clientOptions.middleware;return a.resolveCodeLens?a.resolveCodeLens(i,n,s):s(i,n)}:void 0};return[U.registerCodeLensProvider(e.documentSelector,t),t]}},DH=class extends Ge{constructor(e){super(e,D.DocumentFormattingRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"formatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentFormattingProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentFormattingEdits:(i,n,o)=>{let s=this._client,a=(u,c,f)=>{let p={textDocument:{uri:u.uri},options:c};return s.sendRequest(D.DocumentFormattingRequest.type,p,f).then(d=>d,d=>(s.logFailedRequest(D.DocumentFormattingRequest.type,d),Promise.resolve([])))},l=s.clientOptions.middleware;return l.provideDocumentFormattingEdits?l.provideDocumentFormattingEdits(i,n,o,a):a(i,n,o)}};return[U.registerDocumentFormatProvider(e.documentSelector,t,this._client.clientOptions.formatterPriority),t]}},SH=class extends Ge{constructor(e){super(e,D.DocumentRangeFormattingRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"rangeFormatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentRangeFormattingProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentRangeFormattingEdits:(i,n,o,s)=>{let a=this._client,l=(c,f,p,d)=>{let h={textDocument:{uri:c.uri},range:f,options:p};return a.sendRequest(D.DocumentRangeFormattingRequest.type,h,d).then(m=>m,m=>(a.logFailedRequest(D.DocumentRangeFormattingRequest.type,m),Promise.resolve([])))},u=a.clientOptions.middleware;return u.provideDocumentRangeFormattingEdits?u.provideDocumentRangeFormattingEdits(i,n,o,s,l):l(i,n,o,s)}};return[U.registerDocumentRangeFormatProvider(e.documentSelector,t),t]}},EH=class extends Ge{constructor(e){super(e,D.DocumentOnTypeFormattingRequest.type)}fillClientCapabilities(e){re(re(e,"textDocument"),"onTypeFormatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentOnTypeFormattingProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideOnTypeFormattingEdits:(o,s,a,l,u)=>{let c=this._client,f=(d,h,m,y,v)=>{let x={textDocument:vv(d),position:h,ch:m,options:y};return c.sendRequest(D.DocumentOnTypeFormattingRequest.type,x,v).then(w=>w,w=>(c.logFailedRequest(D.DocumentOnTypeFormattingRequest.type,w),Promise.resolve([])))},p=c.clientOptions.middleware;return p.provideOnTypeFormattingEdits?p.provideOnTypeFormattingEdits(o,s,a,l,u,f):f(o,s,a,l,u)}},i=e.moreTriggerCharacter||[],n=[e.firstTriggerCharacter,...i];return[U.registerOnTypeFormattingEditProvider(e.documentSelector,t,n),t]}},CH=class extends Ge{constructor(e){super(e,D.RenameRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"rename");t.dynamicRegistration=!0,t.prepareSupport=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.renameProvider);!i||(Tl(e.renameProvider)&&(i.prepareProvider=!1),this.register(this.messages,{id:$e(),registerOptions:i}))}registerLanguageProvider(e){let t={provideRenameEdits:(i,n,o,s)=>{let a=this._client,l=(c,f,p,d)=>{let h={textDocument:{uri:c.uri},position:f,newName:p};return a.sendRequest(D.RenameRequest.type,h,d).then(m=>m,m=>(a.logFailedRequest(D.RenameRequest.type,m),Promise.reject(new Error(m.message))))},u=a.clientOptions.middleware;return u.provideRenameEdits?u.provideRenameEdits(i,n,o,s,l):l(i,n,o,s)},prepareRename:e.prepareProvider?(i,n,o)=>{let s=this._client,a=(u,c,f)=>{let p={textDocument:UE(u),position:c};return s.sendRequest(D.PrepareRenameRequest.type,p,f).then(d=>D.Range.is(d)?d:d&&D.Range.is(d.range)?{range:d.range,placeholder:d.placeholder}:Promise.reject(new Error("The element can't be renamed.")),d=>(s.logFailedRequest(D.PrepareRenameRequest.type,d),Promise.reject(new Error(d.message))))},l=s.clientOptions.middleware;return l.prepareRename?l.prepareRename(i,n,o,a):a(i,n,o)}:void 0};return[U.registerRenameProvider(e.documentSelector,t),t]}},_H=class extends Ge{constructor(e){super(e,D.DocumentLinkRequest.type)}fillClientCapabilities(e){let t=re(re(e,"textDocument"),"documentLink");t.dynamicRegistration=!0,t.tooltipSupport=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentLinkProvider);!i||this.register(this.messages,{id:$e(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentLinks:(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.DocumentLinkRequest.type,{textDocument:{uri:l.uri}},u).then(c=>c,c=>(o.logFailedRequest(D.DocumentLinkRequest.type,c),Promise.resolve([]))),a=o.clientOptions.middleware;return a.provideDocumentLinks?a.provideDocumentLinks(i,n,s):s(i,n)},resolveDocumentLink:e.resolveProvider?(i,n)=>{let o=this._client,s=(l,u)=>o.sendRequest(D.DocumentLinkResolveRequest.type,l,u).then(c=>c,c=>(o.logFailedRequest(D.DocumentLinkResolveRequest.type,c),Promise.resolve(l))),a=o.clientOptions.middleware;return a.resolveDocumentLink?a.resolveDocumentLink(i,n,s):s(i,n)}:void 0};return[U.registerDocumentLinkProvider(e.documentSelector,t),t]}},PH=class{constructor(e){this._client=e;this._listeners=new Map}get messages(){return D.DidChangeConfigurationNotification.type}fillClientCapabilities(e){re(re(e,"workspace"),"didChangeConfiguration").dynamicRegistration=!0}initialize(){var t;let e=(t=this._client.clientOptions.synchronize)==null?void 0:t.configurationSection;e!==void 0&&this.register(this.messages,{id:$e(),registerOptions:{section:e}})}register(e,t){let{section:i}=t.registerOptions,n=b.onDidChangeConfiguration(o=>{typeof i=="string"&&!o.affectsConfiguration(i)||Array.isArray(i)&&!i.some(s=>o.affectsConfiguration(s))||i!=null&&this.onDidChangeConfiguration(t.registerOptions.section)});if(this._listeners.set(t.id,n),bt(i)&&i.endsWith(".settings")){let o=this.getConfiguredSettings(i);if(!o||fm(o))return}i!=null&&this.onDidChangeConfiguration(t.registerOptions.section)}unregister(e){let t=this._listeners.get(e);t&&(this._listeners.delete(e),t.dispose())}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}onDidChangeConfiguration(e){let t=typeof e=="string"&&e.startsWith("languageserver."),i;bt(e)?i=[e]:i=e;let n=s=>{if(s===void 0){this._client.sendNotification(D.DidChangeConfigurationNotification.type,{settings:null});return}this._client.sendNotification(D.DidChangeConfigurationNotification.type,{settings:t?this.getConfiguredSettings(s[0]):this.extractSettingsInformation(s)})},o=this.getMiddleware();o?o(i,n):n(i)}getConfiguredSettings(e){let t=".settings".length;return b.getConfiguration(e.slice(0,-t)).get("settings",{})}extractSettingsInformation(e){function t(n,o){let s=n;for(let a=0;a=0?a=b.getConfiguration(o.substr(0,s)).get(o.substr(s+1)):a=b.getConfiguration(o),a){let l=e[n].split(".");t(i,l)[l[l.length-1]]=a}}return i}getMiddleware(){let e=this._client.clientOptions.middleware;if(e.workspace&&e.workspace.didChangeConfiguration)return e.workspace.didChangeConfiguration}},TH=class{constructor(e){this._client=e;this._commands=new Map}get messages(){return D.ExecuteCommandRequest.type}fillClientCapabilities(e){re(re(e,"workspace"),"executeCommand").dynamicRegistration=!0}initialize(e){!e.executeCommandProvider||this.register(this.messages,{id:$e(),registerOptions:Object.assign({},e.executeCommandProvider)})}register(e,t){let i=this._client,n=i.clientOptions.middleware,o=(s,a)=>{let l={command:s,arguments:a};return i.sendRequest(D.ExecuteCommandRequest.type,l).then(void 0,u=>{throw i.logFailedRequest(D.ExecuteCommandRequest.type,u),u})};if(t.registerOptions.commands){let s=[];for(let a of t.registerOptions.commands)s.push(me.registerCommand(a,(...l)=>n.executeCommand?n.executeCommand(a,l,o):o(a,l),null,!0));this._commands.set(t.id,s)}}unregister(e){let t=this._commands.get(e);t&&t.forEach(i=>i.dispose())}dispose(){this._commands.forEach(e=>{e.forEach(t=>t.dispose())}),this._commands.clear()}},Hp;(function(e){function r(t){return t&&D.MessageReader.is(t.reader)&&D.MessageWriter.is(t.writer)}e.is=r})(Hp||(Hp={}));var GE=class{constructor(e,t){this._resolve=e;this._reject=t;this._used=!1}get isUsed(){return this._used}resolve(){this._used=!0,this._resolve()}reject(e){this._used=!0,this._reject(e)}},yv=class{constructor(e,t,i){this._features=[];this._method2Message=new Map;this._dynamicFeatures=new Map;this._id=e,this._name=t,i.outputChannel?this._outputChannel=i.outputChannel:this._outputChannel=void 0,this._clientOptions={disableWorkspaceFolders:i.disableWorkspaceFolders,disableSnippetCompletion:i.disableSnippetCompletion,disableDynamicRegister:i.disableDynamicRegister,disableDiagnostics:i.disableDiagnostics,disableCompletion:i.disableCompletion,formatterPriority:i.formatterPriority,ignoredRootPaths:i.ignoredRootPaths,documentSelector:i.documentSelector||[],synchronize:i.synchronize||{},diagnosticCollectionName:i.diagnosticCollectionName,outputChannelName:i.outputChannelName||this._id,revealOutputChannelOn:i.revealOutputChannelOn||4,stdioEncoding:i.stdioEncoding||"utf8",initializationOptions:i.initializationOptions,initializationFailedHandler:i.initializationFailedHandler,progressOnInitialization:!!i.progressOnInitialization,errorHandler:i.errorHandler||new HE(this._id),middleware:i.middleware||{},workspaceFolder:i.workspaceFolder},this.state=0,this._connectionPromise=void 0,this._resolvedConnection=void 0,this._initializeResult=void 0,this._listeners=void 0,this._providers=void 0,this._diagnostics=void 0,this._fileEvents=[],this._fileEventDelayer=new BE(250),this._onReady=new Promise((o,s)=>{this._onReadyCallbacks=new GE(o,s)}),this._onStop=void 0,this._stateChangeEmitter=new D.Emitter,this._tracer={log:(o,s)=>{bt(o)?this.logTrace(o,s):this.logObjectTrace(o)}},this._syncedDocuments=new Map;let n=b.getConfiguration("coc.preferences");this._markdownSupport=n.get("enableMarkdown",!0),this.registerBuiltinFeatures()}get supporedMarkupKind(){return this._markdownSupport?[D.MarkupKind.Markdown,D.MarkupKind.PlainText]:[D.MarkupKind.PlainText]}get state(){return this._state}get id(){return this._id}get name(){return this._name}set state(e){let t=this.getPublicState();this._state=e;let i=this.getPublicState();i!==t&&this._stateChangeEmitter.fire({oldState:t,newState:i})}getPublicState(){return this.state===3?2:this.state===1?3:1}get initializeResult(){return this._initializeResult}async sendRequest(e,...t){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{return this._resolvedConnection.sendRequest(e,...t)}catch(i){throw this.error(`Sending request ${bt(e)?e:e.method} failed.`,i),i}}onRequest(e,t){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{this._resolvedConnection.onRequest(e,t)}catch(i){throw this.error(`Registering request handler ${bt(e)?e:e.method} failed.`,i),i}}sendNotification(e,t){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{this._resolvedConnection.sendNotification(e,t)}catch(i){throw this.error(`Sending notification ${bt(e)?e:e.method} failed.`,i),i}}onNotification(e,t){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{this._resolvedConnection.onNotification(e,t)}catch(i){throw this.error(`Registering notification handler ${bt(e)?e:e.method} failed.`,i),i}}onProgress(e,t,i){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{if(e==D.WorkDoneProgress.type){let n=this._clientOptions.middleware.handleWorkDoneProgress;if(n!==void 0)return this._resolvedConnection.onProgress(e,t,o=>{n(t,o,()=>i(o))})}return this._resolvedConnection.onProgress(e,t,i)}catch(n){throw this.error(`Registering progress handler for token ${t} failed.`,n),n}}sendProgress(e,t,i){if(!this.isConnectionActive())throw new Error("Language client is not ready yet");try{this._resolvedConnection.sendProgress(e,t,i)}catch(n){throw this.error(`Sending progress for token ${t} failed.`,n),n}}get clientOptions(){return this._clientOptions}get onDidChangeState(){return this._stateChangeEmitter.event}get outputChannel(){if(!this._outputChannel){let{outputChannelName:e}=this._clientOptions;this._outputChannel=C.createOutputChannel(e||this._name)}return this._outputChannel}get diagnostics(){return this._diagnostics}createDefaultErrorHandler(){return new HE(this._id)}set trace(e){this._trace=e,this.onReady().then(()=>{this.resolveConnection().then(t=>{t.trace(this._trace,this._tracer,{sendNotification:!1,traceFormat:this._traceFormat})})},()=>{})}logObjectTrace(e){e.isLSPMessage&&e.type?this.outputChannel.append(`[LSP - ${new Date().toLocaleTimeString()}] `):this.outputChannel.append(`[Trace - ${new Date().toLocaleTimeString()}] `),e&&this.outputChannel.appendLine(`${JSON.stringify(e)}`)}data2String(e){if(e instanceof D.ResponseError){let t=e;return` Message: ${t.message} + Code: ${t.code} ${t.data?` +`+t.data.toString():""}`}return e instanceof Error?bt(e.stack)?e.stack:e.message:bt(e)?e:e.toString()}_appendOutput(e,t,i){let n=3;switch(e){case"Info":n=1;break;case"Warn":n=2;break}this.outputChannel.appendLine(`[${e} - ${new Date().toLocaleTimeString()}] ${t}`);let o;i&&(o=this.data2String(i),this.outputChannel.appendLine(o)),this._clientOptions.revealOutputChannelOn<=n&&this.outputChannel.show(!0)}info(e,t){this._appendOutput("Info",e,t)}warn(e,t){this._appendOutput("Warn",e,t)}error(e,t){this._appendOutput("Error",e,t)}logTrace(e,t){this.outputChannel.appendLine(`[Trace - ${new Date().toLocaleTimeString()}] ${e}`),t&&this.outputChannel.appendLine(this.data2String(t))}needsStart(){return this.state===0||this.state===4||this.state===5}needsStop(){return this.state===1||this.state===3}onReady(){return this._onReady}get started(){return this.state!=0}isConnectionActive(){return this.state===3&&!!this._resolvedConnection}start(){if(this._onReadyCallbacks.isUsed&&(this._onReady=new Promise((e,t)=>{this._onReadyCallbacks=new GE(e,t)})),this._listeners=[],this._providers=[],!this._diagnostics){let e=this._clientOptions,t=e.diagnosticCollectionName?e.diagnosticCollectionName:this._id;this._diagnostics=U.createDiagnosticCollection(t)}return this.state=1,this.resolveConnection().then(e=>(e.onLogMessage(t=>{let i;switch(t.type){case D.MessageType.Error:i="error",this.error(t.message);break;case D.MessageType.Warning:i="warning",this.warn(t.message);break;case D.MessageType.Info:i="info",this.info(t.message);break;default:i="log",this.outputChannel.appendLine(t.message)}if(global.hasOwnProperty("__TEST__")){console.log(`[${i}] ${t.message}`);return}}),e.onShowMessage(t=>{switch(t.type){case D.MessageType.Error:C.showErrorMessage(t.message);break;case D.MessageType.Warning:C.showWarningMessage(t.message);break;case D.MessageType.Info:C.showInformationMessage(t.message);break;default:C.showInformationMessage(t.message)}}),e.onRequest(D.ShowMessageRequest.type,t=>{let i;switch(t.type){case D.MessageType.Error:i=C.showErrorMessage.bind(C);break;case D.MessageType.Warning:i=C.showWarningMessage.bind(C);break;case D.MessageType.Info:i=C.showInformationMessage.bind(C);break;default:i=C.showInformationMessage.bind(C)}let n=t.actions||[];return i(t.message,...n)}),e.onTelemetry(t=>{}),e.listen(),this.initialize(e))).then(void 0,e=>{this.state=2,this._onReadyCallbacks.reject(e),this.error("Starting client failed ",e)}),D.Disposable.create(()=>{this.needsStop()&&this.stop()})}resolveConnection(){return this._connectionPromise||(this._connectionPromise=this.createConnection()),this._connectionPromise}resolveRootPath(){if(this._clientOptions.workspaceFolder)return $.parse(this._clientOptions.workspaceFolder.uri).fsPath;let{ignoredRootPaths:e}=this._clientOptions,t=b.getConfiguration(this.id),i=t.get("rootPatterns",[]),n=t.get("requireRootPattern",!1),o;if(i&&i.length){let a=b.getDocument(b.bufnr);if(a&&a.schema=="file"){let l=WE.default.dirname($.parse(a.uri).fsPath);o=Jf(l,i,b.cwd)}}if(n&&!o)return null;let s=o||b.rootPath||b.cwd;return e&&e.indexOf(s)!==-1?(C.showMessage(`Ignored rootPath ${s} of client "${this._id}"`,"warning"),null):s}initialize(e){this.refreshTrace(e,!1);let{initializationOptions:t,progressOnInitialization:i}=this._clientOptions,n=this.resolveRootPath();if(!n)return;let o={processId:process.pid,rootPath:n||null,rootUri:n?Wp($.file(n)):null,capabilities:this.computeClientCapabilities(),initializationOptions:Lo(t)?t():t,trace:D.Trace.toString(this._trace),workspaceFolders:null,clientInfo:{name:"coc.nvim",version:b.version}};if(this.fillInitializeParams(o),i){let s=$e();o.workDoneToken=s;let a=new Up(e,s);return a.begin({title:`initializing ${this.id}`,kind:"begin"}),this.doInitialize(e,o).then(l=>(a.done(),l),l=>{throw a.cancel(),l})}else return this.doInitialize(e,o)}doInitialize(e,t){return e.initialize(t).then(i=>{this._resolvedConnection=e,this._initializeResult=i,this.state=3;let n;return cm(i.capabilities.textDocumentSync)?i.capabilities.textDocumentSync===D.TextDocumentSyncKind.None?n={openClose:!1,change:D.TextDocumentSyncKind.None,save:void 0}:n={openClose:!0,change:i.capabilities.textDocumentSync,save:{includeText:!1}}:i.capabilities.textDocumentSync!=null&&(n=i.capabilities.textDocumentSync),this._capabilities=Object.assign({},i.capabilities,{resolvedTextDocumentSync:n}),this._clientOptions.disableDiagnostics||e.onDiagnostics(o=>this.handleDiagnostics(o)),e.onRequest(D.RegistrationRequest.type,o=>this.handleRegistrationRequest(o)),e.onRequest("client/registerFeature",o=>this.handleRegistrationRequest(o)),e.onRequest(D.UnregistrationRequest.type,o=>this.handleUnregistrationRequest(o)),e.onRequest("client/unregisterFeature",o=>this.handleUnregistrationRequest(o)),e.onRequest(D.ApplyWorkspaceEditRequest.type,o=>this.handleApplyWorkspaceEdit(o)),e.sendNotification(D.InitializedNotification.type,{}),this.hookFileEvents(e),this.hookConfigurationChanged(e),this.initializeFeatures(e),this._onReadyCallbacks.resolve(),i}).then(void 0,i=>{throw this._clientOptions.initializationFailedHandler?this._clientOptions.initializationFailedHandler(i)?this.initialize(e):(this.stop(),this._onReadyCallbacks.reject(i)):i instanceof D.ResponseError&&i.data&&i.data.retry?C.showPrompt(i.message+" Retry?").then(n=>{n?this.initialize(e):(this.stop(),this._onReadyCallbacks.reject(i))}):(i&&i.message&&C.showMessage(i.message,"error"),this.error("Server initialization failed.",i),this.stop(),this._onReadyCallbacks.reject(i)),i})}stop(){return this._initializeResult=void 0,this._connectionPromise?this.state===4&&this._onStop?this._onStop:(this.state=4,this.cleanUp(),this._onStop=this.resolveConnection().then(e=>e.shutdown().then(()=>{e.exit(),e.dispose(),this.state=5,this.cleanUpChannel(),this._onStop=void 0,this._connectionPromise=void 0,this._resolvedConnection=void 0})).catch(e=>{as.error("Error on stop languageserver:",e),this.state=5,this.cleanUpChannel(),this._onStop=void 0,this._connectionPromise=void 0,this._resolvedConnection=void 0})):(this.state=5,Promise.resolve())}cleanUp(e=!0,t=!0){this._listeners&&(this._listeners.forEach(i=>i.dispose()),this._listeners=void 0),this._providers&&(this._providers.forEach(i=>i.dispose()),this._providers=void 0);for(let i of this._features.values())typeof i.dispose=="function"?i.dispose():as.error("Feature can't be disposed",i);this._syncedDocuments&&this._syncedDocuments.clear(),e&&this.cleanUpChannel(),this._diagnostics&&(t?(this._diagnostics.dispose(),this._diagnostics=void 0):this._diagnostics.clear())}cleanUpChannel(){this._outputChannel&&(this._outputChannel.dispose(),this._outputChannel=void 0)}notifyFileEvent(e){var o;let t=this;function i(s){t._fileEvents.push(s),t._fileEventDelayer.trigger(()=>{t.onReady().then(()=>{t.resolveConnection().then(a=>{t.isConnectionActive()&&a.didChangeWatchedFiles({changes:t._fileEvents}),t._fileEvents=[]})},a=>{t.error("Notify file events failed.",a)})})}let n=(o=this.clientOptions.middleware)==null?void 0:o.workspace;(n==null?void 0:n.didChangeWatchedFile)?n.didChangeWatchedFile(e,i):i(e)}handleDiagnostics(e){if(!this._diagnostics)return;let{uri:t,diagnostics:i}=e,n=this.clientOptions.middleware.handleDiagnostics;n?n(t,i,(o,s)=>this.setDiagnostics(o,s)):this.setDiagnostics(t,i)}setDiagnostics(e,t){var n;if(!this._diagnostics)return;if(b.getConfiguration("diagnostic").get("separateRelatedInformationAsDiagnostics")&&t.length>0){let o=new Map;o.set(e,t);for(let s of t){if((n=s.relatedInformation)==null?void 0:n.length){let a=`${s.message} + +Related diagnostics: +`;for(let l of s.relatedInformation){let u=WE.default.basename($.parse(l.location.uri).fsPath),c=l.location.range.start.line;a=`${a} +${u}(line ${c+1}): ${l.message}`;let f=o.get(l.location.uri)||[];f.push(D.Diagnostic.create(l.location.range,l.message,D.DiagnosticSeverity.Hint,s.code,s.source)),o.set(l.location.uri,f)}s.message=a}this._diagnostics.set(Array.from(o))}}else this._diagnostics.set(e,t)}createConnection(){let e=(i,n,o)=>{as.error("connection error:",i,n),this.handleConnectionError(i,n,o)},t=()=>{this.handleConnectionClosed()};return this.createMessageTransports(this._clientOptions.stdioEncoding||"utf8").then(i=>uye(i.reader,i.writer,e,t))}handleConnectionClosed(){if(this.state===4||this.state===5)return;try{this._resolvedConnection&&this._resolvedConnection.dispose()}catch(t){}let e=1;try{e=this._clientOptions.errorHandler.closed()}catch(t){}this._connectionPromise=void 0,this._resolvedConnection=void 0,e===1?(this.error("Connection to server got closed. Server will not be restarted."),this.state=5,this.cleanUp(!1,!0)):e===2&&(this.info("Connection to server got closed. Server will restart."),this.cleanUp(!1,!0),this.state=0,this.start())}restart(){this.cleanUp(!0,!1),this.start()}handleConnectionError(e,t,i){this._clientOptions.errorHandler.error(e,t,i)===2&&(this.error("Connection to server is erroring. Shutting down server."),this.stop())}hookConfigurationChanged(e){b.onDidChangeConfiguration(()=>{this.refreshTrace(e,!0)})}refreshTrace(e,t=!1){let i=b.getConfiguration(this._id),n=D.Trace.Off,o=D.TraceFormat.Text;if(i){let s=i.get("trace.server","off");typeof s=="string"?n=D.Trace.fromString(s):(n=D.Trace.fromString(i.get("trace.server.verbosity","off")),o=D.TraceFormat.fromString(i.get("trace.server.format","text")))}this._trace=n,this._traceFormat=o,e.trace(this._trace,this._tracer,{sendNotification:t,traceFormat:this._traceFormat})}hookFileEvents(e){let t=this._clientOptions.synchronize.fileEvents;if(!t)return;let i;Array.isArray(t)?i=t:i=[t],!!i&&this._dynamicFeatures.get(D.DidChangeWatchedFilesNotification.type.method).registerRaw($e(),i)}registerFeatures(e){for(let t of e)this.registerFeature(t)}registerFeature(e){if(this._features.push(e),zE.is(e)){let t=e.messages;if(Array.isArray(t))for(let i of t)this._method2Message.set(i.method,i),this._dynamicFeatures.set(i.method,e);else this._method2Message.set(t.method,t),this._dynamicFeatures.set(t.method,e)}}getFeature(e){return this._dynamicFeatures.get(e)}registerBuiltinFeatures(){this.registerFeature(new PH(this)),this.registerFeature(new nH(this,this._syncedDocuments)),this.registerFeature(new sH(this)),this.registerFeature(new aH(this)),this.registerFeature(new lH(this)),this.registerFeature(new uH(this)),this.registerFeature(new oH(this,this._syncedDocuments)),this.registerFeature(new cH(this,e=>this.notifyFileEvent(e))),this._clientOptions.disableCompletion||this.registerFeature(new pH(this)),this.registerFeature(new dH(this)),this.registerFeature(new hH(this)),this.registerFeature(new mH(this)),this.registerFeature(new gH(this)),this.registerFeature(new vH(this)),this.registerFeature(new yH(this)),this.registerFeature(new bH(this)),this.registerFeature(new wH(this)),this.registerFeature(new xH(this)),this.registerFeature(new DH(this)),this.registerFeature(new SH(this)),this.registerFeature(new EH(this)),this.registerFeature(new CH(this)),this.registerFeature(new _H(this)),this.registerFeature(new TH(this))}fillInitializeParams(e){for(let t of this._features)Lo(t.fillInitializeParams)&&t.fillInitializeParams(e)}computeClientCapabilities(){let e={};re(e,"workspace").applyEdit=!0;let t=re(re(e,"workspace"),"workspaceEdit");t.documentChanges=!0,t.resourceOperations=[D.ResourceOperationKind.Create,D.ResourceOperationKind.Rename,D.ResourceOperationKind.Delete],t.failureHandling=D.FailureHandlingKind.TextOnlyTransactional;let i=re(re(e,"textDocument"),"publishDiagnostics");i.relatedInformation=!0,i.versionSupport=!1,i.tagSupport={valueSet:[D.DiagnosticTag.Unnecessary,D.DiagnosticTag.Deprecated]};for(let n of this._features)n.fillClientCapabilities(e);return e}initializeFeatures(e){let t=this._clientOptions.documentSelector;for(let i of this._features)i.initialize(this._capabilities,t)}handleRegistrationRequest(e){return this.clientOptions.disableDynamicRegister?Promise.resolve():new Promise((t,i)=>{for(let n of e.registrations){let o=this._dynamicFeatures.get(n.method);if(!o){i(new Error(`No feature implementation for ${n.method} found. Registration failed.`));return}let s=n.registerOptions||{};s.documentSelector=s.documentSelector||this._clientOptions.documentSelector;let a={id:n.id,registerOptions:s};o.register(this._method2Message.get(n.method),a)}t()})}handleUnregistrationRequest(e){return new Promise((t,i)=>{for(let n of e.unregisterations){let o=this._dynamicFeatures.get(n.method);if(!o){i(new Error(`No feature implementation for ${n.method} found. Unregistration failed.`));return}o.unregister(n.id)}t()})}handleApplyWorkspaceEdit(e){let t=e.edit,i=new Map;b.textDocuments.forEach(o=>i.set(o.uri.toString(),o));let n=!1;if(t.documentChanges){for(let o of t.documentChanges)if(D.TextDocumentEdit.is(o)&&o.textDocument.version&&o.textDocument.version>=0){let s=i.get(o.textDocument.uri);if(s&&s.version!==o.textDocument.version){n=!0;break}}}return n?Promise.resolve({applied:!1}):b.applyEdit(e.edit).then(o=>({applied:o}))}logFailedRequest(e,t){t instanceof D.ResponseError&&t.code===D.ErrorCodes.RequestCancelled||this.error(`Request ${e.method} failed.`,t)}};var Da=S(W());"use strict";function RH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var VE=class extends Ge{constructor(e){super(e,Da.DocumentColorRequest.type)}fillClientCapabilities(e){RH(RH(e,"textDocument"),"colorProvider").dynamicRegistration=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.colorProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideColorPresentations:(i,n,o)=>{let s=this._client,a=(u,c,f)=>{let p={color:u,textDocument:{uri:c.document.uri},range:c.range};return s.sendRequest(Da.ColorPresentationRequest.type,p,f).then(d=>d,d=>(s.logFailedRequest(Da.ColorPresentationRequest.type,d),Promise.resolve(null)))},l=s.clientOptions.middleware;return l.provideColorPresentations?l.provideColorPresentations(i,n,o,a):a(i,n,o)},provideDocumentColors:(i,n)=>{let o=this._client,s=(l,u)=>{let c={textDocument:{uri:l.uri}};return o.sendRequest(Da.DocumentColorRequest.type,c,u).then(f=>f,f=>(o.logFailedRequest(Da.ColorPresentationRequest.type,f),Promise.resolve(null)))},a=o.clientOptions.middleware;return a.provideDocumentColors?a.provideDocumentColors(i,n,s):s(i,n)}};return[U.registerDocumentColorProvider(e.documentSelector,t),t]}};var kH=S(W());var ije=j()("languageclient-configuration"),KE=class{constructor(e){this._client=e;var i;let t=(i=this._client.clientOptions.synchronize)==null?void 0:i.configurationSection;typeof t=="string"&&t.startsWith("languageserver.")&&(this.languageserverSection=t)}fillClientCapabilities(e){e.workspace=e.workspace||{},e.workspace.configuration=!0}initialize(){let e=this._client;e.onRequest(kH.ConfigurationRequest.type,(t,i)=>{let n=s=>{let a=[];for(let l of s.items)a.push(this.getConfiguration(l.scopeUri,l.section));return a},o=e.clientOptions.middleware.workspace;return o&&o.configuration?o.configuration(t,i,n):n(t,i)})}getConfiguration(e,t){let i=null;if(t){this.languageserverSection&&(t=`${this.languageserverSection}.${t}`);let n=t.lastIndexOf(".");if(n===-1)i=b.getConfiguration(void 0,e).get(t,{});else{let o=b.getConfiguration(t.substr(0,n),e);o&&(i=o.get(t.substr(n+1)))}}else{let n=b.getConfiguration(this.languageserverSection,e);i={};for(let o of Object.keys(n))n.has(o)&&(i[o]=JE(n.get(o)))}return i}dispose(){}};function JE(r){if(r){if(Array.isArray(r))return r.map(JE);if(typeof r=="object"){let e=Object.create(null);for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=JE(r[t]));return e}}return r}var bv=S(W());"use strict";function IH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var YE=class extends Ge{constructor(e){super(e,bv.DeclarationRequest.type)}fillClientCapabilities(e){let t=IH(IH(e,"textDocument"),"declaration");t.dynamicRegistration=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.declarationProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideDeclaration:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(bv.DeclarationRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(bv.DeclarationRequest.type,p),Promise.resolve(null))),l=s.clientOptions.middleware;return l.provideDeclaration?l.provideDeclaration(i,n,o,a):a(i,n,o)}};return[U.registerDeclarationProvider(e.documentSelector,t),t]}};var wv=S(W());"use strict";function FH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var XE=class extends Ge{constructor(e){super(e,wv.FoldingRangeRequest.type)}fillClientCapabilities(e){let t=FH(FH(e,"textDocument"),"foldingRange");t.dynamicRegistration=!0,t.rangeLimit=5e3,t.lineFoldingOnly=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.foldingRangeProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideFoldingRanges:(i,n,o)=>{let s=this._client,a=(u,c,f)=>{let p={textDocument:{uri:u.uri}};return s.sendRequest(wv.FoldingRangeRequest.type,p,f).then(d=>d,d=>(s.logFailedRequest(wv.FoldingRangeRequest.type,d),Promise.resolve(null)))},l=s.clientOptions.middleware;return l.provideFoldingRanges?l.provideFoldingRanges(i,n,o,a):a(i,n,o)}};return[U.registerFoldingRangeProvider(e.documentSelector,t),t]}};var xv=S(W());function AH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var ZE=class extends Ge{constructor(e){super(e,xv.ImplementationRequest.type)}fillClientCapabilities(e){let t=AH(AH(e,"textDocument"),"implementation");t.dynamicRegistration=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.implementationProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideImplementation:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(xv.ImplementationRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(xv.ImplementationRequest.type,p),Promise.resolve(null))),l=s.clientOptions.middleware;return l.provideImplementation?l.provideImplementation(i,n,o,a):a(i,n,o)}};return[U.registerImplementationProvider(e.documentSelector,t),t]}};var OH=S(W());"use strict";function fye(r,e){return r[e]===void 0&&(r[e]=Object.create(null)),r[e]}var QE=class{constructor(e){this._client=e;this.activeParts=new Set}fillClientCapabilities(e){fye(e,"window").workDoneProgress=!0}initialize(){let e=this._client,t=n=>{this.activeParts.delete(n)},i=n=>{this.activeParts.add(new Up(this._client,n.token,t))};e.onRequest(OH.WorkDoneProgressCreateRequest.type,i)}dispose(){for(let e of this.activeParts)e.done();this.activeParts.clear()}};var Dv=S(W());function LH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var eC=class extends Ge{constructor(e){super(e,Dv.TypeDefinitionRequest.type)}fillClientCapabilities(e){let t=LH(LH(e,"textDocument"),"typeDefinition");t.dynamicRegistration=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.typeDefinitionProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideTypeDefinition:(i,n,o)=>{let s=this._client,a=(u,c,f)=>s.sendRequest(Dv.TypeDefinitionRequest.type,En(u,c),f).then(p=>p,p=>(s.logFailedRequest(Dv.TypeDefinitionRequest.type,p),Promise.resolve(null))),l=s.clientOptions.middleware;return l.provideTypeDefinition?l.provideTypeDefinition(i,n,o,a):a(i,n,o)}};return[U.registerTypeDefinitionProvider(e.documentSelector,t),t]}};var zp=S(W());"use strict";var EUe=j()("language-client-workspaceFolder");function tC(r,e){if(r!==void 0)return r[e]}function MH(r,e){return r.filter(t=>!e.includes(t))}var rC=class{constructor(e){this._client=e;this._listeners=new Map}get messages(){return zp.DidChangeWorkspaceFoldersNotification.type}asProtocol(e){return e===void 0?null:{uri:e.uri,name:e.name}}fillInitializeParams(e){let t=b.workspaceFolders;this._initialFolders=t,t===void 0?e.workspaceFolders=null:e.workspaceFolders=t.map(i=>this.asProtocol(i)),e.workspaceFolders=b.workspaceFolders}fillClientCapabilities(e){e.workspace=e.workspace||{},e.workspace.workspaceFolders=!0}initialize(e){let t=this._client;t.onRequest(zp.WorkspaceFoldersRequest.type,o=>{let s=()=>{let l=b.workspaceFolders;return l===void 0?null:l.map(c=>this.asProtocol(c))},a=t.clientOptions.middleware.workspace;return a&&a.workspaceFolders?a.workspaceFolders(o,s):s(o)});let i=tC(tC(tC(e,"workspace"),"workspaceFolders"),"changeNotifications"),n;typeof i=="string"?n=i:i===!0&&(n=$e()),n&&this.register(this.messages,{id:n,registerOptions:void 0})}doSendEvent(e,t){let i={event:{added:e.map(n=>this.asProtocol(n)),removed:t.map(n=>this.asProtocol(n))}};this._client.sendNotification(zp.DidChangeWorkspaceFoldersNotification.type,i)}sendInitialEvent(e){if(this._initialFolders&&e){let t=MH(this._initialFolders,e),i=MH(e,this._initialFolders);(i.length>0||t.length>0)&&this.doSendEvent(i,t)}else this._initialFolders?this.doSendEvent([],this._initialFolders):e&&this.doSendEvent(e,[])}register(e,t){let i=t.id,n=this._client,o=b.onDidChangeWorkspaceFolders(s=>{let a=u=>{this.doSendEvent(u.added,u.removed)},l=n.clientOptions.middleware.workspace;l&&l.didChangeWorkspaceFolders?l.didChangeWorkspaceFolders(s,a):a(s)});this._listeners.set(i,o),this.sendInitialEvent(b.workspaceFolders)}unregister(e){let t=this._listeners.get(e);t!==void 0&&(this._listeners.delete(e),t.dispose())}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}};var Sv=S(W());"use strict";function NH(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var iC=class extends Ge{constructor(e){super(e,Sv.SelectionRangeRequest.type)}fillClientCapabilities(e){let t=NH(NH(e,"textDocument"),"selectionRange");t.dynamicRegistration=!0}initialize(e,t){let[i,n]=this.getRegistration(t,e.selectionRangeProvider);!i||!n||this.register(this.messages,{id:i,registerOptions:n})}registerLanguageProvider(e){let t={provideSelectionRanges:(i,n,o)=>{let s=this._client,a=(u,c,f)=>{let p={textDocument:{uri:u.uri},positions:c};return s.sendRequest(Sv.SelectionRangeRequest.type,p,f).then(d=>d,d=>(s.logFailedRequest(Sv.SelectionRangeRequest.type,d),Promise.resolve(null)))},l=s.clientOptions.middleware;return l.provideSelectionRanges?l.provideSelectionRanges(i,n,o,a):a(i,n,o)}};return[U.registerSelectionRangeProvider(e.documentSelector,t),t]}};var l6e=Sa.default.ChildProcess,io=j()("language-client-index"),oC;(function(e){function r(t){return bt(t.command)}e.is=r})(oC||(oC={}));var Gt;(function(r){r[r.stdio=0]="stdio",r[r.ipc=1]="ipc",r[r.pipe=2]="pipe",r[r.socket=3]="socket"})(Gt||(Gt={}));var Ev;(function(e){function r(t){let i=t;return i&&i.kind===3&&cm(i.port)}e.isSocket=r})(Ev||(Ev={}));var sC;(function(e){function r(t){return bt(t.module)}e.is=r})(sC||(sC={}));var aC;(function(e){function r(t){let i=t;return i&&i.writer!==void 0&&i.reader!==void 0}e.is=r})(aC||(aC={}));var lC;(function(e){function r(t){let i=t;return i&&i.process!==void 0&&typeof i.detached=="boolean"}e.is=r})(lC||(lC={}));var Cv=class extends yv{constructor(e,t,i,n,o){let s,a,l,u,c;bt(t)?(s=e,a=t,l=i,u=n,c=!!o):(s=e.toLowerCase(),a=e,l=t,u=i,c=n),c===void 0&&(c=!1),super(s,a,u),this._serverOptions=l,this._forceDebug=c,this.registerProposedFeatures()}stop(){return super.stop().then(()=>{if(this._serverProcess){let e=this._serverProcess;this._serverProcess=void 0,(this._isDetached===void 0||!this._isDetached)&&this.checkProcessDied(e),this._isDetached=void 0}})}get serviceState(){let e=this._state;switch(e){case be.Initial:return ye.Initial;case be.Running:return ye.Running;case be.StartFailed:return ye.StartFailed;case be.Starting:return ye.Starting;case be.Stopped:return ye.Stopped;case be.Stopping:return ye.Stopping;default:return io.error(`Unknown state: ${e}`),ye.Stopped}}static stateName(e){switch(e){case be.Initial:return"Initial";case be.Running:return"Running";case be.StartFailed:return"StartFailed";case be.Starting:return"Starting";case be.Stopped:return"Stopped";case be.Stopping:return"Stopping";default:return"Unknonw"}}checkProcessDied(e){if(!(!e||global.hasOwnProperty("__TEST__"))){if(global.hasOwnProperty("__TEST__")){process.kill(e.pid,0);return}setTimeout(()=>{try{process.kill(e.pid,0),U4(e)}catch(t){}},2e3)}}handleConnectionClosed(){this._serverProcess=void 0,super.handleConnectionClosed()}createMessageTransports(e){function t(a){return a?Object.assign({},process.env,a):process.env}function i(){let a=process.execArgv;return a?a.some(l=>/^--debug=?/.test(l)||/^--debug-brk=?/.test(l)||/^--inspect=?/.test(l)||/^--inspect-brk=?/.test(l)):!1}let n=this._serverOptions;if(Lo(n))return n().then(a=>{if(Hp.is(a))return this._isDetached=!!a.detached,a;if(aC.is(a))return this._isDetached=!!a.detached,{reader:new Et.StreamMessageReader(a.reader),writer:new Et.StreamMessageWriter(a.writer)};{let l;return lC.is(a)?(l=a.process,this._isDetached=a.detached):(l=a,this._isDetached=!1),l.stderr.on("data",u=>this.appendOutput(u,e)),{reader:new Et.StreamMessageReader(l.stdout),writer:new Et.StreamMessageWriter(l.stdin)}}});let o=n,s=n;return s.run||s.debug?typeof v8debug=="object"||this._forceDebug||i()?o=s.debug:o=s.run:o=n,this._getServerWorkingDir(o.options).then(a=>{if(sC.is(o)&&o.module){let l=o,u=l.transport||0,c=[],f=l.options||Object.create(null),p=l.runtime||process.execPath;f.execArgv&&f.execArgv.forEach(m=>c.push(m)),u!=1&&c.push(l.module),l.args&&l.args.forEach(m=>c.push(m));let d=Object.create(null);d.cwd=a,d.env=t(f.env);let h;if(u===1?(d.stdio=[null,null,null],c.push("--node-ipc")):u===0?c.push("--stdio"):u===2?(h=Et.generateRandomPipeName(),c.push(`--pipe=${h}`)):Ev.isSocket(u)&&c.push(`--socket=${u.port}`),c.push(`--clientProcessId=${process.pid.toString()}`),u===1){let m={cwd:a,env:t(f.env),stdio:[null,null,null,"ipc"],execPath:p,execArgv:f.execArgv||[]},y=Sa.default.fork(l.module,c,m);return!y||!y.pid?Promise.reject(`Launching server module "${l.module}" failed.`):(y.on("error",v=>{io.error(v)}),io.info(`${this.id} started with ${y.pid}`),this._serverProcess=y,y.stdout.on("data",v=>this.appendOutput(v,e)),y.stderr.on("data",v=>this.appendOutput(v,e)),{reader:new Et.IPCMessageReader(y),writer:new Et.IPCMessageWriter(y)})}else if(u===0){let m=Sa.default.spawn(p,c,d);return!m||!m.pid?Promise.reject(`Launching server module "${l.module}" failed.`):(io.info(`${this.id} started with ${m.pid}`),m.on("error",y=>{io.error(`Process ${p} error: `,y)}),this._serverProcess=m,m.stderr.on("data",y=>this.appendOutput(y,e)),{reader:new Et.StreamMessageReader(m.stdout),writer:new Et.StreamMessageWriter(m.stdin)})}else{if(u==2)return Promise.resolve(Et.createClientPipeTransport(h)).then(m=>{let y=Sa.default.spawn(p,c,d);return!y||!y.pid?Promise.reject(`Launching server module "${l.module}" failed.`):(io.info(`Language server ${this.id} started with ${y.pid}`),this._serverProcess=y,y.stderr.on("data",v=>this.appendOutput(v,e)),y.stdout.on("data",v=>this.appendOutput(v,e)),Promise.resolve(m.onConnected()).then(v=>({reader:v[0],writer:v[1]})))});if(Ev.isSocket(l.transport))return Promise.resolve(Et.createClientSocketTransport(l.transport.port)).then(m=>{let y=Sa.default.spawn(p,c,d);return!y||!y.pid?Promise.reject(`Launching server ${l.module} failed.`):(y.on("exit",v=>{v!=0&&this.error(`command "${p} ${c.join(" ")}" exited with code: ${v}`)}),io.info(`Language server ${this.id} started with ${y.pid}`),this._serverProcess=y,y.stderr.on("data",v=>this.appendOutput(v,e)),y.stdout.on("data",v=>this.appendOutput(v,e)),Promise.resolve(m.onConnected()).then(v=>({reader:v[0],writer:v[1]})))})}}else if(oC.is(o)&&o.command){let l=o,u=l.args||[],c=Object.assign({},l.options);c.env=c.env?Object.assign({},process.env,c.env):process.env,c.cwd=a;let f=b.expand(o.command),p=Sa.default.spawn(f,u,c);return p.on("error",d=>{this.error(d.message),io.error(d)}),!p||!p.pid?Promise.reject(`Launching server "${this.id}" using command ${l.command} failed.`):(io.info(`Language server "${this.id}" started with ${p.pid}`),p.on("exit",d=>{d!=0&&this.error(`${l.command} exited with code: ${d}`)}),p.stderr.on("data",d=>this.appendOutput(d,e)),this._serverProcess=p,this._isDetached=!!c.detached,{reader:new Et.StreamMessageReader(p.stdout),writer:new Et.StreamMessageWriter(p.stdin)})}return Promise.reject(`Unsupported server configuration ${JSON.stringify(n,null,2)}`)})}registerProposedFeatures(){this.registerFeatures(_v.createAll(this))}registerBuiltinFeatures(){super.registerBuiltinFeatures(),this.registerFeature(new KE(this)),this.registerFeature(new eC(this)),this.registerFeature(new ZE(this)),this.registerFeature(new YE(this)),this.registerFeature(new VE(this)),this.registerFeature(new XE(this)),this.registerFeature(new iC(this)),this.registerFeature(new QE(this)),this.clientOptions.disableWorkspaceFolders||this.registerFeature(new rC(this))}_getServerWorkingDir(e){let t=e&&e.cwd;return t&&!nC.default.isAbsolute(t)&&(t=nC.default.join(b.cwd,t)),t||(t=b.cwd),t?new Promise(i=>{qH.default.lstat(t,(n,o)=>{i(!n&&o.isDirectory()?t:void 0)})}):Promise.resolve(void 0)}appendOutput(e,t){let i=bt(e)?e:e.toString(t);this.outputChannel.append(i.endsWith(` +`)?i:i+` +`)}},$H=class{constructor(e,t){this._client=e;this._setting=t;this._listeners=[]}start(){return b.onDidChangeConfiguration(e=>{e.affectsConfiguration(this._setting)&&this.onDidChangeConfiguration()},null,this._listeners),this.onDidChangeConfiguration(),{dispose:()=>{z(this._listeners),this._client.needsStop()&&this._client.stop()}}}onDidChangeConfiguration(){let e=this._setting.indexOf("."),t=e>=0?this._setting.substr(0,e):this._setting,i=e>=0?this._setting.substr(e+1):void 0,n=i?b.getConfiguration(t).get(i,!0):b.getConfiguration(t);n&&this._client.needsStart()?this._client.start():!n&&this._client.needsStop()&&this._client.stop()}},_v;(function(e){function r(t){return[]}e.createAll=r})(_v||(_v={}));var Ea=j()("services");function pye(r){switch(r){case ye.Initial:return"init";case ye.Running:return"running";case ye.Starting:return"starting";case ye.StartFailed:return"startFailed";case ye.Stopping:return"stopping";case ye.Stopped:return"stopped";default:return"unknown"}}var WH=class extends BH.EventEmitter{constructor(){super(...arguments);this.registered=new Map;this.disposables=[]}init(){b.onDidOpenTextDocument(e=>{this.start(e)},null,this.disposables),b.onDidChangeConfiguration(e=>{e.affectsConfiguration("languageserver")&&this.createCustomServices()},null,this.disposables),this.createCustomServices()}dispose(){this.removeAllListeners(),z(this.disposables);for(let e of this.registered.values())e.dispose()}regist(e){let{id:t}=e;if(t||Ea.error("invalid service configuration. ",e.name),!this.registered.get(t))return this.registered.set(t,e),Ea.info(`registered service "${t}"`),this.shouldStart(e)&&e.start(),e.state==ye.Running&&this.emit("ready",t),e.onServiceReady(()=>{Ea.info(`service ${t} started`),this.emit("ready",t)},null,this.disposables),Ru.Disposable.create(()=>{e.stop(),e.dispose(),this.registered.delete(t)})}getService(e){let t=this.registered.get(e);return t||(t=this.registered.get(`languageserver.${e}`)),t}shouldStart(e){if(e.state!=ye.Initial)return!1;let t=e.selector;for(let i of b.documents)if(b.match(t,i.textDocument))return!0;return!1}start(e){let t=this.getServices(e);for(let i of t)i.state==ye.Initial&&i.start()}getServices(e){let t=[];for(let i of this.registered.values())b.match(i.selector,e)>0&&t.push(i);return t}stop(e){let t=this.registered.get(e);if(!t){C.showMessage(`Service ${e} not found`,"error");return}return Promise.resolve(t.stop())}stopAll(){for(let e of this.registered.values())e.stop()}async toggle(e){let t=this.registered.get(e);if(!t){C.showMessage(`Service ${e} not found`,"error");return}let{state:i}=t;try{i==ye.Running?await Promise.resolve(t.stop()):i==ye.Initial?await t.start():i==ye.Stopped&&await t.restart()}catch(n){C.showMessage(`Service error: ${n.message}`,"error")}}getServiceStats(){let e=[];for(let[t,i]of this.registered)e.push({id:t,languageIds:dye(i.selector),state:pye(i.state)});return e}createCustomServices(){let e=b.getConfiguration().get("languageserver",{});for(let t of Object.keys(e)){let i=e[t];this.registLanguageClient(t,i)}}waitClient(e){let t=this.getService(e);return t&&t.state==ye.Running?Promise.resolve():t?new Promise(i=>{t.onServiceReady(()=>{i()})}):new Promise(i=>{let n=o=>{(o==e||o==`languageserver.${e}`)&&(this.off("ready",n),i())};this.on("ready",n)})}async registNotification(e,t){await this.waitClient(e);let i=this.getService(e);if(!i.client){C.showMessage(`Not a language client: ${e}`,"error");return}i.client.onNotification(t,async o=>{await b.nvim.call("coc#do_notify",[e,t,o])})}async sendNotification(e,t,i){if(!t)throw new Error("method required for ontification");let n=this.getService(e);if(!n||!n.client)throw new Error(`Language server ${e} not found`);if(n.state==ye.Starting&&await n.client.onReady(),n.state!=ye.Running)throw new Error(`Language server ${e} not running`);await Promise.resolve(n.client.sendNotification(t,i))}async sendRequest(e,t,i,n){if(!t)throw new Error("method required for sendRequest");let o=this.getService(e);if(o||await He(100),o=this.getService(e),!o||!o.client)throw new Error(`Language server ${e} not found`);if(o.state==ye.Starting&&await o.client.onReady(),o.state!=ye.Running)throw new Error(`Language server ${e} not running`);return n||(n=new Ru.CancellationTokenSource().token),await Promise.resolve(o.client.sendRequest(t,i,n))}registLanguageClient(e,t){let i=typeof e=="string"?`languageserver.${e}`:e.id,n=[],o=new Ru.Emitter,s=typeof e=="string"?null:e;if(this.registered.has(i))return;let a=!1,l={id:i,client:s,name:typeof e=="string"?e:e.name,selector:typeof e=="string"?HH(t.filetypes,t.additionalSchemes):e.clientOptions.documentSelector,state:ye.Initial,onServiceReady:o.event,start:()=>{if(l.state==ye.Starting||l.state==ye.Running||s&&!s.needsStart())return;if(a&&s)return s.restart(),Promise.resolve();if(!a){if(typeof e=="string"&&!s){let c=b.getConfiguration().get("languageserver",{})[e];if(!c||c.enable===!1)return;let f=hye(i,e,c);if(!f)return;s=new Cv(i,e,f[1],f[0]),l.selector=f[0].documentSelector,l.client=s}s.onDidChangeState(c=>{let{oldState:f,newState:p}=c;p==ni.Starting?l.state=ye.Starting:p==ni.Running?l.state=ye.Running:p==ni.Stopped&&(l.state=ye.Stopped);let d=zH(f),h=zH(p);Ea.info(`${s.name} state change: ${d} => ${h}`)},null,n),a=!0}l.state=ye.Starting,Ea.debug(`starting service: ${i}`);let u=s.start();return n.push(u),new Promise(c=>{s.onReady().then(()=>{o.fire(void 0),c()},f=>{C.showMessage(`Server ${i} failed to start: ${f}`,"error"),Ea.error(`Server ${i} failed to start:`,f),l.state=ye.StartFailed,c()})})},dispose:async()=>{o.dispose(),z(n)},stop:async()=>{!s||!s.needsStop()||await Promise.resolve(s.stop())},restart:async()=>{s?(l.state=ye.Starting,s.restart()):await l.start()}};return this.regist(l)}};function dye(r){let e=r.map(t=>typeof t=="string"?t:t.language);return e=e.filter(t=>typeof t=="string"),Array.from(new Set(e))}function hye(r,e,t){let{command:i,module:n,port:o,args:s,filetypes:a}=t;if(s=s||[],!a)return C.showMessage(`Wrong configuration of LS "${e}", filetypes not found`,"error"),null;if(!i&&!n&&!o)return C.showMessage(`Wrong configuration of LS "${e}", no command or module specified.`,"error"),null;let l;if(n){if(n=b.expand(n),!jH.default.existsSync(n))return C.showMessage(`Module file "${n}" not found for LS "${e}"`,"error"),null;l={module:n,runtime:t.runtime||process.execPath,args:s,transport:gye(t),options:vye(t)}}else i?l={command:i,args:s,options:yye(t)}:o&&(l=()=>new Promise((d,h)=>{let m=new UH.default.Socket,y=t.host||"127.0.0.1";Ea.info(`languageserver "${r}" connecting to ${y}:${o}`),m.connect(o,y,()=>{d({reader:m,writer:m})}),m.on("error",v=>{h(new Error(`Connection error for ${r}: ${v.message}`))})}));let u=!!t.disableWorkspaceFolders,c=!!t.disableSnippetCompletion;return[{ignoredRootPaths:(t.ignoredRootPaths||[]).map(d=>b.expand(d)),disableWorkspaceFolders:u,disableSnippetCompletion:c,disableDynamicRegister:!!t.disableDynamicRegister,disableCompletion:!!t.disableCompletion,disableDiagnostics:!!t.disableDiagnostics,formatterPriority:t.formatterPriority||0,documentSelector:HH(t.filetypes,t.additionalSchemes),revealOutputChannelOn:mye(t.revealOutputChannelOn),synchronize:{configurationSection:`${r}.settings`},diagnosticCollectionName:e,outputChannelName:r,stdioEncoding:t.stdioEncoding||"utf8",progressOnInitialization:t.progressOnInitialization!==!1,initializationOptions:t.initializationOptions||{}},l]}function mye(r){switch(r){case"info":return ii.Info;case"warn":return ii.Warn;case"error":return ii.Error;case"never":return ii.Never;default:return ii.Never}}function HH(r,e){let t=[],i=["file","untitled"].concat(e||[]);return r?(r.forEach(n=>{t.push(...i.map(o=>({language:n,scheme:o})))}),t):i.map(n=>({scheme:n}))}function gye(r){let{transport:e,transportPort:t}=r;return!e||e=="ipc"?Gt.ipc:e=="stdio"?Gt.stdio:e=="pipe"?Gt.pipe:{kind:Gt.socket,port:t}}function vye(r){return{cwd:r.cwd,execArgv:r.execArgv||[],env:r.env||void 0}}function yye(r){return{cwd:r.cwd,detached:!!r.detached,shell:!!r.shell,env:r.env||void 0}}function zH(r){switch(r){case ni.Running:return"running";case ni.Starting:return"starting";case ni.Stopped:return"stopped";default:return"unknown"}}var Vt=new WH;var Nz=S(Gr()),Xp=S(W());var GH=S(require("events")),Ca=["","","","","","","","","","","","","","","","","","","<2-LeftMouse>","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],uC=class extends GH.EventEmitter{constructor(){super();this.configuration=b.getConfiguration("list"),this.disposable=b.onDidChangeConfiguration(e=>{e.affectsConfiguration("list")&&(this.configuration=b.getConfiguration("list"),this.emit("change"))})}get(e,t){return this.configuration.get(e,t)}get previousKey(){return this.fixKey(this.configuration.get("previousKeymap",""))}get nextKey(){return this.fixKey(this.configuration.get("nextKeymap",""))}dispose(){this.disposable.dispose(),this.removeAllListeners()}fixKey(e){if(Ca.includes(e))return e;let t=Ca.find(i=>i.toLowerCase()==e.toLowerCase());return t||(C.showMessage(`Configured key "${e}" not supported.`,"error"),null)}},Pv=uC;var T6e=S(gh());var F6e=j()("list-mappings"),cC=class{constructor(e,t,i){this.manager=e;this.nvim=t;this.config=i;this.insertMappings=new Map;this.normalMappings=new Map;this.userInsertMappings=new Map;this.userNormalMappings=new Map;let{prompt:n}=e;this.add("insert","",()=>{n.removeTail()}),this.add("insert","",()=>{var o;(o=e.session)==null||o.history.next()}),this.add("insert","",()=>{var o;(o=e.session)==null||o.history.previous()}),this.add("insert","",async()=>{await n.paste()}),this.add("insert","",()=>e.switchMatcher()),this.add("insert",["",""],async()=>{await e.doAction()}),this.add("insert",["",""," "],()=>e.chooseAction()),this.add("insert","",()=>{e.toggleMode()}),this.add("insert","",()=>{e.stop()}),this.add("insert","",()=>e.cancel()),this.add("insert","",async()=>{var o;await((o=e.session)==null?void 0:o.reloadItems())}),this.add("insert","",()=>{n.moveLeft()}),this.add("insert","",()=>{n.moveRight()}),this.add("insert",["",""],()=>{n.moveToEnd()}),this.add("insert",["",""],()=>{n.moveToStart()}),this.add("insert",["","",""],()=>{n.onBackspace()}),this.add("insert","",()=>{n.removeWord()}),this.add("insert","",()=>{n.removeAhead()}),this.add("insert","",()=>n.insertRegister()),this.add("insert","",()=>e.feedkeys("",!1)),this.add("insert","",()=>e.feedkeys("",!1)),this.add("insert","",()=>e.feedkeys("",!1)),this.add("insert","",()=>e.normal("j")),this.add("insert","",()=>e.normal("k")),this.add("insert",[""],this.doScroll.bind(this,"")),this.add("insert",[""],this.doScroll.bind(this,"")),this.add("insert",[""],this.doScroll.bind(this,"")),this.add("insert",[""],this.doScroll.bind(this,"")),this.add("normal","",()=>{}),this.add("normal","t",()=>e.doAction("tabe")),this.add("normal","s",()=>e.doAction("split")),this.add("normal","d",()=>e.doAction("drop")),this.add("normal",["","","\r"],()=>e.doAction()),this.add("normal","",()=>{var o;return(o=e.session)==null?void 0:o.ui.selectAll()}),this.add("normal"," ",()=>{var o;return(o=e.session)==null?void 0:o.ui.toggleSelection()}),this.add("normal","p",()=>e.togglePreview()),this.add("normal",[""," ",""],()=>e.chooseAction()),this.add("normal","",()=>{e.stop()}),this.add("normal","",()=>e.cancel()),this.add("normal","",()=>{var o;return(o=e.session)==null?void 0:o.reloadItems()}),this.add("normal","",()=>{var o;return(o=e.session)==null?void 0:o.jumpBack()}),this.add("normal","",()=>this.scrollPreview("down")),this.add("normal","",()=>this.scrollPreview("up")),this.add("normal",["i","I","o","O","a","A"],()=>e.toggleMode()),this.add("normal","?",()=>{var o;return(o=e.session)==null?void 0:o.showHelp()}),this.add("normal",":",async()=>{await e.cancel(!1),await t.eval('feedkeys(":")')}),this.add("normal",[""],this.doScroll.bind(this,"")),this.add("normal",[""],this.doScroll.bind(this,"")),this.createMappings(),i.on("change",()=>{this.createMappings()})}createMappings(){let e=this.config.get("insertMappings",{});this.userInsertMappings=this.fixUserMappings(e);let t=this.config.get("normalMappings",{});this.userNormalMappings=this.fixUserMappings(t)}fixUserMappings(e){let t=new Map;for(let[i,n]of Object.entries(e))if(i.length==1)t.set(i,n);else if(i.startsWith("<")&&i.endsWith(">"))if(i.toLowerCase()=="")t.set(" ",n);else if(i.toLowerCase()=="")t.set("",n);else if(Ca.includes(i))t.set(i,n);else{let o=!1;for(let s=0;s"),{cusorIndex:t,interactive:i,input:n,_matcher:o}=this,s=['echo ""'];if(this.mode=="insert")if(i?s.push("echohl MoreMsg | echon 'INTERACTIVE ' | echohl None"):o&&s.push(`echohl MoreMsg | echon '${o.toUpperCase()} ' | echohl None`),s.push(`echohl Special | echon '${e} ' | echohl None`),t==n.length)s.push(`echon '${n.replace(/'/g,"''")}'`),s.push("echohl Cursor | echon ' ' | echohl None");else{let l=n.slice(0,t);l&&s.push(`echon '${l.replace(/'/g,"''")}'`),s.push(`echohl Cursor | echon '${n[t].replace(/'/,"''")}' | echohl None`);let u=n.slice(t+1);s.push(`echon '${u.replace(/'/g,"''")}'`)}else s.push('echohl MoreMsg | echo "" | echohl None');s.push("redraw");let a=s.join("|");this.nvim.command(a,!0)}moveLeft(){this.cusorIndex!=0&&(this.cusorIndex=this.cusorIndex-1,this.drawPrompt())}moveRight(){this.cusorIndex!=this._input.length&&(this.cusorIndex=this.cusorIndex+1,this.drawPrompt())}moveToEnd(){this.cusorIndex!=this._input.length&&(this.cusorIndex=this._input.length,this.drawPrompt())}moveToStart(){this.cusorIndex!=0&&(this.cusorIndex=0,this.drawPrompt())}onBackspace(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(0,e),n=t.slice(e);this.cusorIndex=e-1,this._input=`${i.slice(0,i.length-1)}${n}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeNext(){let{cusorIndex:e,input:t}=this;if(e==t.length-1)return;let i=t.slice(0,e),n=t.slice(e+1);this._input=`${i}${n}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeWord(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(0,e),n=t.slice(e),o=i.replace(/[\w$]+([^\w$]+)?$/,"");this.cusorIndex=e-(i.length-o.length),this._input=`${o}${n}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeTail(){let{cusorIndex:e,input:t}=this;if(e==t.length)return;let i=t.slice(0,e);this._input=i,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeAhead(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(e);this.cusorIndex=0,this._input=i,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}async acceptCharacter(e){if(this.requestInput){if(this.requestInput=!1,/^[0-9a-z"%#*+/:\-.]$/.test(e)){let t=await this.nvim.call("getreg",e);t=t.replace(/\n/g," "),this.addText(t)}}else this.addText(e)}insertRegister(){this.requestInput=!0}async paste(){let e=await this.nvim.eval("@*");e=e.replace(/\n/g,""),!!e&&this.addText(e)}async eval(e){let t=await this.nvim.call("eval",[e]);t=t.replace(/\n/g,""),this.addText(t)}addText(e){let{cusorIndex:t,input:i}=this;this.cusorIndex=t+e.length;let n=i.slice(0,t),o=i.slice(t);this._input=`${n}${e}${o}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}},JH=fC;var gC=S(Gr()),sz=S(W());function no(r){let e=[];for(let t=0,i=r.length;t=97&&r<=122||r>=65&&r<=90}function nn(r,e){return r==e||r>=97&&r<=122&&e+32===r}function Vp(r,e){let t=r.charCodeAt(0),i=e.charCodeAt(0);return t===i||t>=97&&t<=122&&i+32===t}function ku(r,e){let t=r.length;if(r.length>e.length)return!1;let i=0;for(let n=0;n=97&&s<=122&&o+32===s){i=i+1;continue}}return i===t}var B6e=j()("list-history"),pC=class{constructor(e,t){this.prompt=e;this.name=t;this.index=-1;this.loaded=[];this.current=[];this.db=b.createDatabase(`list-${t}-history`),this.key=Buffer.from(b.cwd).toString("base64")}filter(){let{input:e}=this.prompt;if(e==this.curr)return;this.historyInput="";let t=no(e);this.current=this.loaded.filter(i=>ku(t,i)),this.index=-1}get curr(){return this.index==-1?null:this.current[this.index]}load(e){let{db:t}=this;e=e||"";let i=t.fetch(this.key);!i||!Array.isArray(i)?this.loaded=[]:this.loaded=i,this.index=-1,this.current=this.loaded.filter(n=>n.startsWith(e))}add(){let{loaded:e,db:t,prompt:i}=this,{input:n}=i;if(!n||n.length<2||n==this.historyInput)return;let o=e.indexOf(n);o!=-1&&e.splice(o,1),e.push(n),e.length>200&&(e=e.slice(-200)),t.push(this.key,e)}previous(){let{current:e,index:t}=this;!e||!e.length||(t<=0?this.index=e.length-1:this.index=t-1,this.historyInput=this.prompt.input=e[this.index]||"")}next(){let{current:e,index:t}=this;!e||!e.length||(t==e.length-1?this.index=0:this.index=t+1,this.historyInput=this.prompt.input=e[this.index]||"")}},YH=pC;var XH=S(Gr()),Iu=S(W());var Y6e=j()("list-ui"),dC=class{constructor(e,t,i,n){this.nvim=e;this.name=t;this.listOptions=i;this.config=n;this.newTab=!1;this.currIndex=0;this.drawCount=0;this.items=[];this.disposables=[];this.selected=new Set;this.mutex=new ar;this._onDidChangeLine=new Iu.Emitter;this._onDidOpen=new Iu.Emitter;this._onDidClose=new Iu.Emitter;this._onDidLineChange=new Iu.Emitter;this._onDoubleClick=new Iu.Emitter;this.onDidChangeLine=this._onDidChangeLine.event;this.onDidLineChange=this._onDidLineChange.event;this.onDidOpen=this._onDidOpen.event;this.onDidClose=this._onDidClose.event;this.onDidDoubleClick=this._onDoubleClick.event;this.signOffset=n.get("signOffset"),this.matchHighlightGroup=n.get("matchHighlightGroup","Search"),this.newTab=i.position=="tab",A.on("BufWinLeave",async s=>{s!=this.bufnr||this.window==null||(this.window=null,this._onDidClose.fire(s))},null,this.disposables),A.on("CursorMoved",async(s,a)=>{s==this.bufnr&&this.onLineChange(a[0]-1)},null,this.disposables);let o=XH.default(async s=>{if(s!=this.bufnr)return;let[a,l,u]=await e.eval('[win_getid(),line("w0"),line("w$")]');u<300||!this.window||a!=this.window.id||(e.pauseNotification(),this.doHighlight(l-1,u),e.command("redraw",!0),e.resumeNotification(!1,!0))},100);this.disposables.push({dispose:()=>{o.clear()}}),A.on("CursorMoved",o,null,this.disposables)}get limitLines(){return this.config.get("limitLines",3e4)}onLineChange(e){this.currIndex!=e&&(this.currIndex=e,this._onDidChangeLine.fire(e))}set index(e){if(e<0||e>=this.items.length)return;let{nvim:t}=this;t.pauseNotification(),this.setCursor(e+1,0),t.command("redraw",!0),t.resumeNotification(!1,!0).logError()}get index(){return this.currIndex}get firstItem(){return this.items[0]}get lastItem(){return this.items[this.items.length-1]}getItem(e){return this.items[e]}get item(){let{window:e}=this;return e?e.cursor.then(t=>(this.currIndex=t[0]-1,this.items[this.currIndex]),t=>null):Promise.resolve(null)}async echoMessage(e){if(this.bufnr)return;let{items:t}=this,n=`[${t.indexOf(e)+1}/${t.length}] ${e.label||""}`;this.nvim.callTimer("coc#util#echo_lines",[[n]],!0)}async updateItem(e,t){if(!this.bufnr||b.bufnr!=this.bufnr)return;let i=Object.assign({resolved:!0},e);if(t0&&this.bufnr){i.pauseNotification();for(let o of t)i.command(`sign place ${n+o} line=${o} name=CocSelected buffer=${this.bufnr}`,!0);await i.resumeNotification()}}async toggleSelection(){let{nvim:e,selected:t,signOffset:i,bufnr:n}=this;if(b.bufnr!=n)return;let o=await e.call("line","."),s=await e.call("mode");if(s=="v"||s=="V"){let[l,u]=await this.getSelectedRange(),c=t.has(l);l>u&&([l,u]=[u,l]);for(let p=l;p<=u;p++)c?(t.delete(p),e.command(`sign unplace ${i+p} buffer=${n}`,!0)):(t.add(p),e.command(`sign place ${i+p} line=${p} name=CocSelected buffer=${n}`,!0));this.setCursor(u,0),e.command("redraw",!0),await e.resumeNotification();return}let a=t.has(o);e.pauseNotification(),a?(t.delete(o),e.command(`sign unplace ${i+o} buffer=${n}`,!0)):(t.add(o),e.command(`sign place ${i+o} line=${o} name=CocSelected buffer=${n}`,!0)),this.setCursor(o+1,0),e.command("redraw",!0),await e.resumeNotification()}async selectLines(e,t){let{nvim:i,signOffset:n,bufnr:o,length:s}=this;this.clearSelection();let{selected:a}=this;i.pauseNotification(),e>t&&([e,t]=[t,e]);for(let u=e;u<=t&&!(u>s);u++)a.add(u),i.command(`sign place ${n+u} line=${u} name=CocSelected buffer=${o}`,!0);this.setCursor(t,0),i.command("redraw",!0),await i.resumeNotification()}async selectAll(){let{length:e}=this;e!=0&&await this.selectLines(1,e)}clearSelection(){let{selected:e,nvim:t,signOffset:i,bufnr:n}=this;if(!!n&&e.size>0){let o=[];for(let s of e)o.push(i+s);t.call("coc#util#unplace_signs",[n,o],!0),this.selected=new Set}}get shown(){return this.window!=null}get bufnr(){var e;return(e=this.buffer)==null?void 0:e.id}get winid(){var e;return(e=this.window)==null?void 0:e.id}get ready(){return this.window?Promise.resolve():new Promise((e,t)=>{let i=setTimeout(()=>{t(new Error("window create timeout"))},3e3),n=this.onDidLineChange(()=>{n.dispose(),clearTimeout(i),e()})})}async drawItems(e,t,i=!1,n){let o=this.drawCount=this.drawCount+1,{nvim:s,name:a,listOptions:l}=this,u=await this.mutex.acquire();if(this.items=e.length>this.limitLines?e.slice(0,this.limitLines):e,this.window==null&&!(n&&n.isCancellationRequested))try{let{position:d,numberSelect:h}=l,[m,y]=await s.call("coc#list#create",[d,t,a,h]);n&&n.isCancellationRequested?s.call("coc#list#clean_up",[],!0):(this.height=t,this.buffer=s.createBuffer(m),this.window=s.createWindow(y),this._onDidOpen.fire(this.bufnr))}catch(d){s.call("coc#prompt#stop_prompt",["list"],!0),s.call("coc#list#clean_up",[],!0),u(),C.showMessage(`Error on list create: ${d.message}`,"error");return}if(u(),n&&n.isCancellationRequested||o!==this.drawCount)return;let f=this.items.map(d=>d.label);this.clearSelection();let p=i?this.currIndex:0;await this.setLines(f,!1,p),this._onDidLineChange.fire(this.currIndex+1)}async appendItems(e){if(!this.window)return;let t=this.items.length;if(t>=this.limitLines)return;let i=this.limitLines-t,n=e.slice(0,i);this.items=this.items.concat(n),await this.setLines(n.map(o=>o.label),t>0,this.currIndex)}async setLines(e,t=!1,i){let{nvim:n,buffer:o,window:s}=this;if(!o||!s)return;if(n.pauseNotification(),!t){let l=this.config.get("statusLineSegments");l&&s.notify("nvim_win_set_option",["statusline",l.join(" ")]),n.call("coc#compat#clear_matches",[s.id],!0),e.length||(e=["No results, press ? on normal mode to get help."],n.call("coc#compat#matchaddpos",["Comment",[[1]],99,this.window.id],!0))}if(o.setOption("modifiable",!0,!0),b.isVim?n.call("coc#list#setlines",[o.id,e,t],!0):o.setLines(e,{start:t?-1:0,end:-1,strictIndexing:!1},!0),o.setOption("modifiable",!1,!0),!t&&i==0)this.doHighlight(0,300);else{let l=this.newTab?b.env.lines:this.height;this.doHighlight(Math.max(0,i-l),Math.min(i+l+1,this.length-1))}t||(this.currIndex=i,s.notify("nvim_win_set_cursor",[[i+1,0]])),n.command("redraws",!0);let a=await n.resumeNotification();Array.isArray(a[1])&&a[1][0]==0&&(this.window=null)}restoreWindow(){if(this.newTab)return;let{winid:e,height:t}=this;e&&t&&this.nvim.call("coc#list#restore",[e,t],!0)}reset(){this.window&&(this.window=null,this.buffer=null)}dispose(){z(this.disposables),this.window=null,this._onDidChangeLine.dispose(),this._onDidOpen.dispose(),this._onDidClose.dispose(),this._onDidLineChange.dispose(),this._onDoubleClick.dispose()}get length(){return this.items.length}get selectedItems(){let{selected:e,items:t}=this,i=[];for(let n of e)t[n-1]&&i.push(t[n-1]);return i}doHighlight(e,t){let{nvim:i}=b,{items:n}=this,o=[];for(let s=e;s<=Math.min(t,n.length-1);s++){let{ansiHighlights:a,highlights:l}=n[s];if(a)for(let u of a){let{span:c,hlGroup:f}=u;o.push({hlGroup:f,priority:9,pos:[s+1,c[0]+1,c[1]-c[0]]})}if(l&&Array.isArray(l.spans)){let{spans:u,hlGroup:c}=l;for(let f of u)o.push({hlGroup:c||this.matchHighlightGroup,priority:11,pos:[s+1,f[0]+1,f[1]-f[0]]})}}i.call("coc#compat#matchaddgroups",[this.window.id,o],!0)}setCursor(e,t){let{window:i,items:n}=this,o=n.length==0?1:n.length;e>o||(this.onLineChange(e-1),i&&i.notify("nvim_win_set_cursor",[[e,t]]))}async getSelectedRange(){let{nvim:e}=this;await e.call("coc#prompt#stop_prompt",["list"]),await e.eval('feedkeys("\\", "in")');let[,t]=await e.call("getpos","'<"),[,i]=await e.call("getpos","'>");return t>i&&([t,i]=[i,t]),this.nvim.call("coc#prompt#start_prompt",["list"],!0),[t,i]}},ZH=dC;var Kp=S(W());var Fu=-Infinity,bye=Infinity,wye=-.005,xye=-.005,Dye=-.01,QH=1,Sye=.9,Eye=.8,Cye=.7,_ye=.6;function Pye(r){return r.toLowerCase()===r}function Tye(r){return r.toUpperCase()===r}function Rye(r){let e=r.length,t=new Array(e),i="/";for(let n=0;n1024)return Fu;let n=new Array(t),o=new Array(t);return ez(r,e,n,o),o[t-1][i-1]}function tz(r,e){let t=r.length,i=e.length,n=new Array(t);if(!t||!i)return n;if(t===i){for(let l=0;l1024)return n;let o=new Array(t),s=new Array(t);ez(r,e,o,s);let a=!1;for(let l=t-1,u=i-1;l>=0;l--)for(;u>=0;u--)if(o[l][u]!==Fu&&(a||o[l][u]===s[l][u])){a=l&&u&&s[l][u]===o[l-1][u-1]+QH,n[l]=u--;break}return n}function rz(r,e){r=r.toLowerCase(),e=e.toLowerCase();let t=r.length;for(let i=0,n=0;ie.score&&(e=r[t]);return e}var Iye=j()("list-worker"),Fye="",mC=class{constructor(e,t,i,n,o){this.nvim=e;this.list=t;this.prompt=i;this.listOptions=n;this.config=o;this._loading=!1;this.totalItems=[];this._onDidChangeItems=new Kp.Emitter;this._onDidChangeLoading=new Kp.Emitter;this.onDidChangeItems=this._onDidChangeItems.event;this.onDidChangeLoading=this._onDidChangeLoading.event}set loading(e){this._loading!=e&&(this._loading=e,this._onDidChangeLoading.fire(e))}get isLoading(){return this._loading}async loadItems(e,t=!1){let{list:i,listOptions:n}=this;this.loading=!0;let{interactive:o}=n;this.tokenSource=new Kp.CancellationTokenSource;let s=this.tokenSource.token,a=await i.loadItems(e,s);if(!s.isCancellationRequested)if(!a||Array.isArray(a)){this.tokenSource=null,a=a||[],this.totalItems=a.map(u=>(u.label=this.fixLabel(u.label),this.parseListItemAnsi(u),u)),this.loading=!1;let l;o?l=this.convertToHighlightItems(a):l=this.filterItems(a),this._onDidChangeItems.fire({items:l,reload:t,finished:!0})}else{let l=a,u=this.totalItems=[],c=0,f=e.input,p,d,h=v=>{if(d=Date.now(),c>=u.length)return;let x=this.input!=f;if(!(o&&x))if(c==0||x){f=this.input,c=u.length;let w;o?w=this.convertToHighlightItems(u):w=this.filterItems(u),this._onDidChangeItems.fire({items:w,reload:t,append:!1,finished:v})}else{let w=u.slice(c);c=u.length;let E;o?E=this.convertToHighlightItems(w):E=this.filterItems(w),this._onDidChangeItems.fire({items:E,append:!0,finished:v})}};l.on("data",v=>{p&&clearTimeout(p),!s.isCancellationRequested&&(o&&this.input!=f||(v.label=this.fixLabel(v.label),this.parseListItemAnsi(v),u.push(v),!d&&u.length==500||Date.now()-d>200?h():p=setTimeout(()=>h(),50)))});let m=()=>{l!=null&&(this.tokenSource=null,l=null,this.loading=!1,y.dispose(),p&&clearTimeout(p),u.length==0?this._onDidChangeItems.fire({items:[],finished:!0}):h(!0))},y=s.onCancellationRequested(()=>{l&&(l.dispose(),m())});l.on("error",async v=>{l!=null&&(l=null,this.tokenSource=null,this.loading=!1,y.dispose(),p&&clearTimeout(p),this.nvim.call("coc#prompt#stop_prompt",["list"],!0),C.showMessage(`Task error: ${v.toString()}`,"error"),Iye.error(v))}),l.on("end",m)}}drawItems(){let{totalItems:e,listOptions:t}=this,i;t.interactive?i=this.convertToHighlightItems(e):i=this.filterItems(e),this._onDidChangeItems.fire({items:i,finished:!0})}stop(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null),this.loading=!1}get length(){return this.totalItems.length}get input(){return this.prompt.input}convertToHighlightItems(e){let{input:t}=this;return t?e.map(i=>{let n=Rv(i);if(n=="")return i;let o=nz(n,t);if(!o||!o.score)return i;let s=this.getHighlights(n,o.matches);return Object.assign({},i,{highlights:s})}):[]}filterItems(e){let{input:t}=this,{sort:i,matcher:n,ignorecase:o}=this.listOptions,s=this.config.extendedSearchMode?Aye(t):[t];if(t.length==0||s.length==0)return e;if(n=="strict"){let u=[];for(let c of e){let f=[],p=Rv(c),d=!0;for(let h of s){let m=o?p.toLowerCase().indexOf(h.toLowerCase()):p.indexOf(h);if(m==-1){d=!1;break}f.push([Vr(p,m),Vr(p,m+ue(h))])}d&&u.push(Object.assign({},c,{highlights:{spans:f}}))}return u}if(n=="regex"){let u=[],c=o?"iu":"u",f=s.reduce((p,d)=>{try{let h=new RegExp(d,c);p.push(h)}catch(h){}return p},[]);for(let p of e){let d=[],h=Rv(p),m=!0;for(let y of f){let v=h.match(y);if(v==null){m=!1;break}d.push([Vr(h,v.index),Vr(h,v.index+ue(v[0]))])}m&&u.push(Object.assign({},p,{highlights:{spans:d}}))}return u}let a=[],l=0;for(let u of e){let c=u.filterText||u.label,f=0,p=[],d=Rv(u),h=!0;for(let y of s){if(!rz(y,c)){h=!1;break}p.push(...tz(y,d)),i&&(f+=Tv(y,c))}if(!h)continue;let m=Object.assign({},u,{sortText:typeof u.sortText=="string"?u.sortText:String.fromCharCode(l),score:f,highlights:this.getHighlights(d,p)});a.push(m),l=l+1}return i&&a.length&&a.sort((u,c)=>u.score!=c.score?c.score-u.score:u.sortText>c.sortText?1:-1),a}getHighlights(e,t){let i=[];if(t&&t.length){let n=t.shift(),o=t.shift(),s=n;for(;o;){if(o==s+1){s=o,o=t.shift();continue}i.push([Vr(e,n),Vr(e,s)+1]),n=o,s=n,o=t.shift()}i.push([Vr(e,n),Vr(e,s)+1])}return{spans:i}}parseListItemAnsi(e){let{label:t}=e;if(e.ansiHighlights||!t.includes(Fye))return;let{line:i,highlights:n}=Nl(t);e.label=i,e.ansiHighlights=n}fixLabel(e){let{columns:t}=b.env;return e=e.split(` +`).join(" "),e.slice(0,t*2)}dispose(){this.stop()}},oz=mC;function Rv(r){return r.filterText!=null?ij(r.filterText,r.label):r.label}function Aye(r){let e=[],t=0,i=0,n="";for(;io.replace(/\\\s/g," ").trim()).filter(o=>o.length>0)}var Oye=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],az=j()("list-session"),vC=class{constructor(e,t,i,n,o=[],s){this.nvim=e;this.prompt=t;this.list=i;this.listOptions=n;this.listArgs=o;this.config=s;this.loadingFrame="";this.hidden=!1;this.disposables=[];this.args=[];this.ui=new ZH(e,i.name,n,s),this.history=new YH(t,i.name),this.worker=new oz(e,i,t,n,{interactiveDebounceTime:s.get("interactiveDebounceTime",100),extendedSearchMode:s.get("extendedSearchMode",!0)}),this.interactiveDebounceTime=s.get("interactiveDebounceTime",100);let a=gC.default(async()=>{let[u,c,f]=await e.eval('[coc#list#has_preview(),win_getid(),line(".")]');u&&c==this.winid&&await this.doPreview(f-1)},50);this.disposables.push({dispose:()=>{a.clear()}}),this.ui.onDidChangeLine(a,null,this.disposables),this.ui.onDidChangeLine(this.resolveItem,this,this.disposables),this.ui.onDidLineChange(this.resolveItem,this,this.disposables);let l=gC.default(async()=>{let{autoPreview:u}=this.listOptions;if(!u){let[c,f]=await e.eval("[coc#list#has_preview(),mode()]");if(!c||f!="n")return}await this.doAction("preview")},50);this.disposables.push({dispose:()=>{l.clear()}}),this.ui.onDidLineChange(l,null,this.disposables),this.ui.onDidLineChange(()=>{this.updateStatus()},null,this.disposables),this.ui.onDidOpen(async()=>{typeof this.list.doHighlight=="function"&&this.list.doHighlight(),this.listOptions.first&&await this.doAction()},null,this.disposables),this.ui.onDidClose(async()=>{await this.hide()},null,this.disposables),this.ui.onDidDoubleClick(async()=>{await this.doAction()},null,this.disposables),this.worker.onDidChangeItems(async({items:u,reload:c,append:f,finished:p})=>{if(!this.hidden)if(f)await this.ui.appendItems(u);else{let d=this.config.get("height",10);p&&!n.interactive&&n.input.length==0&&(d=Math.min(u.length,d));let h=this.uiTokenSource=new sz.CancellationTokenSource;await this.ui.drawItems(u,Math.max(1,d),c,h.token)}},null,this.disposables),this.worker.onDidChangeLoading(u=>{this.hidden||(u?this.interval=setInterval(()=>{let c=Math.floor(new Date().getMilliseconds()/100);this.loadingFrame=Oye[c],this.updateStatus()},100):(this.interval&&(this.loadingFrame="",clearInterval(this.interval),this.interval=null),this.updateStatus()))},null,this.disposables)}async start(e){this.args=e,this.cwd=b.cwd,this.hidden=!1;let{listOptions:t,listArgs:i}=this,n=await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]');this.listArgs=i,this.history.load(t.input||""),this.window=this.nvim.createWindow(n[0]),this.buffer=this.nvim.createBuffer(n[1]),this.savedHeight=n[2],await this.worker.loadItems(this.context)}async reloadItems(){if(!this.window)return;let e=await this.nvim.call("winbufnr",[this.window.id]);e!=-1&&(this.buffer=this.nvim.createBuffer(e),await this.worker.loadItems(this.context,!0))}async call(e){var o,s;await this.nvim.call("coc#prompt#stop_prompt",["list"]);let t=await this.ui.getItems(),i={name:this.name,args:this.listArgs,input:this.prompt.input,winid:(o=this.window)==null?void 0:o.id,bufnr:(s=this.buffer)==null?void 0:s.id,targets:t},n=await this.nvim.call(e,[i]);return this.prompt.start(),n}async chooseAction(){let{nvim:e}=this,{actions:t,defaultAction:i}=this.list,n=t.map(c=>c.name),o=n.indexOf(i);o!=-1&&(n.splice(o,1),n.unshift(i));let s=new Set,a=[],l=[];for(let c of n){let f=0;for(let p of c){if(!s.has(p)){s.add(p),a.push(`${c.slice(0,f)}&${c.slice(f)}`);break}f++}f==c.length&&l.push(c)}l.length&&(az.error(`Can't create shortcut for actions: ${l.join(",")} of "${this.name}" list`),n=n.filter(c=>!l.includes(c))),await e.call("coc#prompt#stop_prompt",["list"]);let u=await e.call("confirm",["Choose action:",a.join(` +`)]);await He(10),this.prompt.start(),u&&await this.doAction(n[u-1])}async doAction(e){let{list:t}=this;e=e||t.defaultAction;let i=t.actions.find(o=>o.name==e);if(!i){C.showMessage(`Action ${e} not found`,"error");return}let n;if(e=="preview"){let o=await this.ui.item;n=o?[o]:[]}else n=await this.ui.getItems();n.length&&await this.doItemAction(n,i)}async doPreview(e){let t=this.ui.getItem(e),i=this.list.actions.find(n=>n.name=="preview");!t||!i||await this.doItemAction([t],i)}async first(){await this.doDefaultAction(0)}async last(){await this.doDefaultAction(this.ui.length-1)}async previous(){await this.doDefaultAction(this.ui.index-1)}async next(){await this.doDefaultAction(this.ui.index+1)}async doDefaultAction(e){let{ui:t}=this,i=t.getItem(e);!i||(t.index=e,await this.doItemAction([i],this.defaultAction),await t.echoMessage(i))}get name(){return this.list.name}get winid(){return this.ui.winid}get length(){return this.ui.length}get defaultAction(){let{defaultAction:e,actions:t}=this.list,i=t.find(n=>n.name==e);if(!i)throw new Error(`default action "${e}" not found`);return i}async hide(){if(this.hidden)return;this.uiTokenSource&&(this.uiTokenSource.cancel(),this.uiTokenSource.dispose(),this.uiTokenSource=null);let{nvim:e,interval:t}=this;t&&clearInterval(t),this.hidden=!0,this.worker.stop(),this.history.add();let{winid:i}=this.ui;this.ui.reset(),this.window&&i&&(await e.call("coc#list#hide",[this.window.id,this.savedHeight,i]),b.isVim&&(e.command("redraw",!0),await He(10))),e.call("coc#prompt#stop_prompt",["list"],!0)}toggleMode(){let e=this.prompt.mode=="normal"?"insert":"normal";this.prompt.mode=e,this.listOptions.mode=e,this.updateStatus()}stop(){this.worker.stop()}async resolveItem(){let e=this.ui.index,t=this.ui.getItem(e);if(!t||t.resolved)return;let{list:i}=this;if(typeof i.resolveItem=="function"){let n=await Promise.resolve(i.resolveItem(t));n&&e==this.ui.index&&await this.ui.updateItem(n,e)}}async showHelp(){await this.hide();let{list:e,nvim:t}=this;if(!e)return;t.pauseNotification(),t.command("tabe +setl\\ previewwindow [LIST HELP]",!0),t.command("setl nobuflisted noswapfile buftype=nofile bufhidden=wipe",!0),await t.resumeNotification();let i=e.options&&e.options.length,n=await t.buffer,o=new ss;if(o.addLine("NAME","Label"),o.addLine(` ${e.name} - ${e.description||""} +`),o.addLine("SYNOPSIS","Label"),o.addLine(` :CocList [LIST OPTIONS] ${e.name}${i?" [ARGUMENTS]":""} +`),e.detail){o.addLine("DESCRIPTION","Label");let a=e.detail.split(` +`).map(l=>" "+l);o.addLine(a.join(` +`)+` +`)}if(i){o.addLine("ARGUMENTS","Label"),o.addLine("");for(let a of e.options)o.addLine(a.name,"Special"),o.addLine(` ${a.description}`),o.addLine("");o.addLine("")}let s=b.getConfiguration(`list.source.${e.name}`);if(Object.keys(s).length){o.addLine("CONFIGURATIONS","Label"),o.addLine("");let a={};ge.all.forEach(l=>{let{packageJSON:u}=l,{contributes:c}=u;if(!c)return;let{configuration:f}=c;if(f){let{properties:p}=f;if(p)for(let d of Object.keys(p))a[d]=p[d]}});for(let l of Object.keys(s)){let u=s[l],c=`list.source.${e.name}.${l}`,f=a[c]&&a[c].description?a[c].description:l;o.addLine(` "${c}"`,"MoreMsg"),o.addText(` - ${f}, current value: `),o.addText(JSON.stringify(u),"Special")}o.addLine("")}o.addLine("ACTIONS","Label"),o.addLine(` ${e.actions.map(a=>a.name).join(", ")}`),o.addLine(""),o.addLine("see ':h coc-list-options' for available list options.","Comment"),t.pauseNotification(),o.render(n,0,-1),t.command("setl nomod",!0),t.command("setl nomodifiable",!0),t.command("normal! gg",!0),t.command("nnoremap q :bd!",!0),await t.resumeNotification()}switchMatcher(){let{matcher:e,interactive:t}=this.listOptions;if(t)return;let i=["fuzzy","strict","regex"],n=i.indexOf(e)+1;n>=i.length&&(n=0),this.listOptions.matcher=i[n],this.prompt.matcher=i[n],this.worker.drawItems()}updateStatus(){let{ui:e,list:t,nvim:i}=this;if(!e.winid)return;let n=i.createBuffer(e.bufnr),o={mode:this.prompt.mode.toUpperCase(),args:this.args.join(" "),name:t.name,cwd:this.cwd,loading:this.loadingFrame,total:this.worker.length};i.pauseNotification(),n.setVar("list_status",o,!0),i.command("redraws",!0),i.resumeNotification(!1,!0).logError()}get context(){let{winid:e}=this.ui;return{options:this.listOptions,args:this.listArgs,input:this.prompt.input,cwd:b.cwd,window:this.window,buffer:this.buffer,listWindow:e?this.nvim.createWindow(e):void 0}}redrawItems(){this.worker.drawItems()}onMouseEvent(e){switch(e){case"":return this.ui.onMouse("mouseDown");case"":return this.ui.onMouse("mouseDrag");case"":return this.ui.onMouse("mouseUp");case"<2-LeftMouse>":return this.ui.onMouse("doubleClick")}}async doNumberSelect(e){if(!this.listOptions.numberSelect)return!1;let t=e.charCodeAt(0);if(t>=48&&t<=57){let i=Number(e);return i==0&&(i=10),this.ui.length>=i&&(this.nvim.pauseNotification(),this.ui.setCursor(Number(e),0),await this.nvim.resumeNotification(),await this.doAction()),!0}return!1}jumpBack(){let{window:e,nvim:t}=this;e&&(t.pauseNotification(),t.call("coc#prompt#stop_prompt",["list"],!0),this.nvim.call("win_gotoid",[e.id],!0),t.resumeNotification(!1,!0).logError())}async resume(){this.winid&&await this.hide();let e=await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]');this.hidden=!1,this.window=this.nvim.createWindow(e[0]),this.buffer=this.nvim.createBuffer(e[1]),this.savedHeight=e[2],this.prompt.start(),await this.ui.resume(),this.listOptions.autoPreview&&await this.doAction("preview")}async doItemAction(e,t){let{noQuit:i}=this.listOptions,{nvim:n}=this,o=t.persist===!0||t.name=="preview",s=this.winid&&(o||i);try{if(s?o||(n.pauseNotification(),n.call("coc#prompt#stop_prompt",["list"],!0),n.call("win_gotoid",[this.context.window.id],!0),await n.resumeNotification()):await this.hide(),t.multiple)await Promise.resolve(t.execute(e,this.context));else if(t.parallel)await Promise.all(e.map(a=>Promise.resolve(t.execute(a,this.context))));else for(let a of e)await Promise.resolve(t.execute(a,this.context));s&&this.ui.restoreWindow(),t.reload&&s&&await this.worker.loadItems(this.context,!0)}catch(a){C.showMessage(a.message,"error"),az.error(`Error on action "${t.name}"`,a)}}onInputChange(){this.timer&&clearTimeout(this.timer);let e=this.worker.length;if(this.listOptions.input=this.prompt.input,this.listOptions.interactive)this.worker.stop(),this.timer=setTimeout(async()=>{await this.worker.loadItems(this.context)},this.interactiveDebounceTime);else if(e){let t=Math.max(Math.min(Math.floor(e/200),300),50);this.timer=setTimeout(()=>{this.worker.drawItems()},t)}}dispose(){if(!this.hidden){this.hidden=!0,this.uiTokenSource&&(this.uiTokenSource.cancel(),this.uiTokenSource.dispose(),this.uiTokenSource=null);let{winid:e}=this.ui;this.ui.reset(),this.window&&e&&this.nvim.call("coc#list#hide",[this.window.id,this.savedHeight,e],!0)}this.interval&&clearInterval(this.interval),this.timer&&clearTimeout(this.timer),z(this.disposables),this.worker.dispose(),this.ui.dispose()}},lz=vC;var dz=S(require("fs")),bC=S(require("path")),hz=S(require("readline")),qr=S(W());var uz=S(require("child_process")),cz=S(require("events")),fz=S(require("readline"));var Lye=j()("list-commandTask"),yC=class extends cz.EventEmitter{constructor(e){super();this.opt=e;this.disposables=[];this.start()}start(){let{cmd:e,args:t,cwd:i,onLine:n}=this.opt,o=uz.spawn(e,t,{cwd:i,windowsHide:!0});this.disposables.push({dispose:()=>{o.kill()}}),o.on("error",a=>{this.emit("error",a.message)}),o.stderr.on("data",a=>{Lye.error(`[${e} Error]`,a.toString("utf8"))});let s=fz.default.createInterface(o.stdout);s.on("line",a=>{let l=n(a);l&&this.emit("data",l)}),s.on("close",()=>{this.emit("end")})}dispose(){z(this.disposables)}},pz=yC;var Mye=j()("list-basic"),wC=class{constructor(e){this.nvim=e;this.defaultAction="open";this.actions=[];this.options=[];this.disposables=[];this.config=new Pv}get alignColumns(){return this.config.get("alignColumns",!1)}get hlGroup(){return this.config.get("previewHighlightGroup","Search")}get previewHeight(){return this.config.get("maxPreviewHeight",12)}get splitRight(){return this.config.get("previewSplitRight",!1)}parseArguments(e){if(!this.optionMap){this.optionMap=new Map;for(let i of this.options){let n=i.name.split(/,\s*/g).map(s=>s.replace(/\s+.*/g,"")),o=i.key?i.key:n[n.length-1].replace(/^-/,"");for(let s of n)this.optionMap.set(s,{name:o,hasValue:i.hasValue})}}let t={};for(let i=0;i{let n=await this.convertLocation(t.location);await this.previewLocation(n,i)}});let{nvim:e}=this;this.createAction({name:"quickfix",multiple:!0,execute:async t=>{let i=await Promise.all(t.map(o=>this.convertLocation(o.location).then(s=>b.getQuickfixItem(s))));await e.call("setqflist",[i]);let n=await e.getVar("coc_quickfix_open_command");e.command(typeof n=="string"?n:"copen",!0)}});for(let t of["open","tabe","drop","vsplit","split"])this.createAction({name:t,execute:async i=>{await this.jumpTo(i.location,t=="open"?null:t)}})}async convertLocation(e){if(typeof e=="string")return qr.Location.create(e,qr.Range.create(0,0,0,0));if(qr.Location.is(e))return e;let t=$.parse(e.uri);if(t.scheme!="file")return qr.Location.create(e.uri,qr.Range.create(0,0,0,0));let i=hz.default.createInterface({input:dz.default.createReadStream(t.fsPath,{encoding:"utf8"})}),n=e.line,o=0,s=!1,a=await new Promise(l=>{i.on("line",u=>{if(!s){if(u.includes(n)){i.removeAllListeners(),i.close(),s=!0,l(u);return}o=o+1}}),i.on("error",u=>{this.nvim.errWriteLine(`Read ${t.fsPath} error: ${u.message}`),l(null)})});if(a!=null){let l=e.text?a.indexOf(e.text):0;l==0&&(l=a.match(/^\s*/)[0].length);let u=qr.Position.create(o,l+(e.text?e.text.length:0));return qr.Location.create(e.uri,qr.Range.create(qr.Position.create(o,l),u))}return qr.Location.create(e.uri,qr.Range.create(0,0,0,0))}async jumpTo(e,t){if(typeof e=="string"){await b.jumpTo(e,null,t);return}let{range:i,uri:n}=await this.convertLocation(e),o=i.start;o.line==0&&o.character==0&&Me(o,i.end)==0&&(o=null),await b.jumpTo(n,o,t)}createAction(e){let{name:t}=e,i=this.actions.findIndex(n=>n.name==t);i!==-1&&this.actions.splice(i,1),this.actions.push(e)}async previewLocation(e,t){if(!t.listWindow)return;let{nvim:i}=this,{uri:n,range:o}=e,s=b.getDocument(e.uri),a=$.parse(n),l=[];if(s)l=s.getLines();else if(a.scheme=="file")try{l=(await Yf(a.fsPath,"utf8")).split(/\r?\n/)}catch(c){""+a.fsPath,c.message}let u={winid:t.window.id,range:Gn(o)?null:o,lnum:o.start.line+1,name:a.scheme=="file"?a.fsPath:n,filetype:s?s.filetype:this.getFiletype(a.fsPath),position:t.options.position,maxHeight:this.previewHeight,splitRight:this.splitRight,hlGroup:this.hlGroup,scheme:a.scheme};await i.call("coc#list#preview",[l,u]),b.isVim&&i.command("redraw",!0)}async preview(e,t){let{nvim:i}=this,{bufname:n,filetype:o,range:s,lines:a,lnum:l}=e,u={winid:t.window.id,lnum:s?s.start.line+1:l||1,filetype:o||"txt",position:t.options.position,maxHeight:this.previewHeight,splitRight:this.splitRight,hlGroup:this.hlGroup};n&&(u.name=n),s&&(u.range=s),await i.call("coc#list#preview",[a,u]),b.isVim&&i.command("redraw",!0)}doHighlight(){}dispose(){z(this.disposables)}getFiletype(e){let t=bC.default.extname(e);if(!t)return"";for(let i of b.documents){let n=$.parse(i.uri).fsPath;if(bC.default.extname(n)==t){let{filetype:o}=i;return o=="javascriptreact"?"javascript":o=="typescriptreact"?"typescript":o.indexOf(".")!==-1?o.split(".")[0]:o}}return""}},Mt=wC;var kv=S(require("path"));function $r(r,e){if(e.length===0)return[];let t=[];if(r){let i=Array(Math.min(...e.map(n=>n.label.length))).fill(0);for(let n of e)for(let o=0;o({...n,label:n.label.map((o,s)=>o.padEnd(i[s])).join(" ")}))}else t=e.map(i=>({...i,label:i.label.join(" ")}));return t}function mz(r,e){var t;if(r==="hidden")return"";if(r==="full")return e;if(r==="short"){let i=e.split(kv.default.sep);return i.length<2?e:[...i.slice(0,i.length-2).filter(o=>o.length>0).map(o=>o[0]),i[i.length-1]].join(kv.default.sep)}else{let i=e.split(kv.default.sep);return(t=i[i.length-1])!=null?t:""}}var xC=class extends Mt{constructor(e){super(e);this.defaultAction="run";this.description="registered commands of coc.nvim";this.name="commands";this.mru=b.createMru("commands"),this.addAction("run",async t=>{let{cmd:i}=t.data;await A.fire("Command",[i]),me.executeCommand(i).logError(),await me.addRecent(i)}),this.addAction("append",async t=>{let{cmd:i}=t.data;await e.feedKeys(`:CocCommand ${i} `,"n",!1)})}async loadItems(e){let t=[],i=await this.mru.load(),{commandList:n,onCommandList:o,titles:s}=me,a=n.map(l=>l.id).concat(o);for(let l of[...new Set(a)])t.push({label:[l,...s.get(l)?[s.get(l)]:[]],filterText:l,data:{cmd:l,score:Nye(i,l)}});return t.sort((l,u)=>u.data.score-l.data.score),$r(this.alignColumns,t)}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocCommandsTitle /\\t.*$/ contained containedin=CocCommandsLine",!0),e.command("highlight default link CocCommandsTitle Comment",!0),e.resumeNotification().catch(t=>{})}},gz=xC;function Nye(r,e){let t=r.indexOf(e);return t==-1?-1:r.length-t}var vz=S(require("path"));var Iv=S(jn()),Jp=S(require("path"));var G8e=j()("list-location"),DC=class extends Mt{constructor(e){super(e);this.defaultAction="open";this.description="show locations saved by g:coc_jump_locations variable";this.name="location";this.addLocationActions()}async loadItems(e,t){let i=await this.nvim.getVar("coc_jump_locations");if(t.isCancellationRequested)return[];i=i||[],i.forEach(a=>{if(!a.uri){let l=Jp.default.isAbsolute(a.filename)?a.filename:Jp.default.join(e.cwd,a.filename);a.uri=$.file(l).toString()}if(!a.bufnr&&b.getDocument(a.uri)!=null&&(a.bufnr=b.getDocument(a.uri).bufnr),a.range)a.lnum=a.lnum||a.range.start.line+1,a.col=a.col||a.range.start.character+1;else{let{lnum:l,col:u}=a;a.range=Iv.Range.create(l-1,u-1,l-1,u-1)}});let n=await this.nvim.call("bufnr","%"),o=i.every(a=>a.bufnr&&n&&a.bufnr==n);return i.map(a=>{let l=o?"":a.filename,u=`${l}${a.text.trim()}`;Jp.default.isAbsolute(l)&&(l=Ye(e.cwd,l)?Jp.default.relative(e.cwd,l):l);let c=`${l} |${a.type?a.type+" ":""}${a.lnum} col ${a.col}| `,f;if(a.range&&a.range.start.line==a.range.end.line){let d=ue(c)+ue(a.text.slice(0,a.range.start.character)),h=ue(c)+ue(a.text.slice(0,a.range.end.character));f={hlGroup:"Search",span:[d,h]}}return{label:c+a.text,location:Iv.Location.create(a.uri,a.range),filterText:u,ansiHighlights:f?[f]:void 0}})}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocLocationName /\\v^[^|]+/ contained containedin=CocLocationLine",!0),e.command("syntax match CocLocationPosition /\\v\\|\\w*\\s?\\d+\\scol\\s\\d+\\|/ contained containedin=CocLocationLine",!0),e.command("syntax match CocLocationError /Error/ contained containedin=CocLocationPosition",!0),e.command("syntax match CocLocationWarning /Warning/ contained containedin=CocLocationPosition",!0),e.command("highlight default link CocLocationName Directory",!0),e.command("highlight default link CocLocationPosition LineNr",!0),e.command("highlight default link CocLocationError Error",!0),e.command("highlight default link CocLocationWarning WarningMsg",!0),e.resumeNotification().catch(t=>{})}},ls=DC;var eWe=j()("list-symbols"),SC=class extends ls{constructor(){super(...arguments);this.defaultAction="open";this.description="diagnostics of current workspace";this.name="diagnostics"}async loadItems(e){let t=St.getDiagnosticList(),{cwd:i}=e,n=this.getConfig().get("includeCode",!0),o=this.getConfig().get("pathFormat","full"),s=t.map(a=>{let l=Ye(i,a.file)?vz.default.relative(i,a.file):a.file,u=mz(o,l),c=o!=="hidden"?[`${u}:${a.lnum}`]:[],f=n?[`[${a.source}${a.code?"":"]"}`,a.code?`${a.code}]`:""]:[];return{label:[...c,...f,a.severity,a.message],location:a.location}});return $r(this.alignColumns,s)}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocDiagnosticsFile /\\v^\\s*\\S+/ contained containedin=CocDiagnosticsLine",!0),e.command("syntax match CocDiagnosticsError /\\tError\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),e.command("syntax match CocDiagnosticsWarning /\\tWarning\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),e.command("syntax match CocDiagnosticsInfo /\\tInformation\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),e.command("syntax match CocDiagnosticsHint /\\tHint\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),e.command("highlight default link CocDiagnosticsFile Comment",!0),e.command("highlight default link CocDiagnosticsError CocErrorSign",!0),e.command("highlight default link CocDiagnosticsWarning CocWarningSign",!0),e.command("highlight default link CocDiagnosticsInfo CocInfoSign",!0),e.command("highlight default link CocDiagnosticsHint CocHintSign",!0),e.resumeNotification().catch(t=>{})}},yz=SC;var Au=S($i()),bz=S(require("os")),Fv=S(require("path"));var qye=j()("list-extensions"),EC=class extends Mt{constructor(e){super(e);this.defaultAction="toggle";this.description="manage coc extensions";this.name="extensions";this.addAction("toggle",async t=>{let{id:i,state:n}=t.data;n!="disabled"&&(n=="activated"?await ge.deactivate(i):await ge.activate(i),await He(100))},{persist:!0,reload:!0,parallel:!0}),this.addAction("configuration",async t=>{let{root:i}=t.data,n=Fv.default.join(i,"package.json");if(Au.default.existsSync(n)){let s=Au.default.readFileSync(n,"utf8").split(/\r?\n/).findIndex(a=>a.includes('"contributes"'));await b.jumpTo($.file(n).toString(),{line:s==-1?0:s,character:0})}}),this.addAction("open",async t=>{let{root:i}=t.data;b.env.isiTerm?e.call("coc#util#iterm_open",[i],!0):e.call("coc#util#open_url",[i],!0)}),this.addAction("disable",async t=>{let{id:i,state:n}=t.data;n!=="disabled"&&await ge.toggleExtension(i)},{persist:!0,reload:!0,parallel:!0}),this.addAction("enable",async t=>{let{id:i,state:n}=t.data;n=="disabled"&&await ge.toggleExtension(i)},{persist:!0,reload:!0,parallel:!0}),this.addAction("lock",async t=>{let{id:i}=t.data;await ge.toggleLock(i)},{persist:!0,reload:!0}),this.addAction("help",async t=>{let{root:i}=t.data,o=(await Au.default.readdir(i)).find(s=>/^readme/i.test(s));if(o){let s=await e.call("fnameescape",[Fv.default.join(i,o)]);await b.callAsync("coc#util#execute",[`edit ${s}`])}}),this.addAction("reload",async t=>{let{id:i}=t.data;await ge.reloadExtension(i)},{persist:!0,reload:!0}),this.addAction("fix",async t=>{let{root:i,isLocal:n}=t.data,{npm:o}=ge;if(n){C.showMessage("Can't fix for local extension.","warning");return}if(!o)return;let s=Fv.default.join(i,"node_modules");Au.default.existsSync(s)&&Au.default.removeSync(s);let a=await b.createTerminal({cwd:i});!await a.show(!1)||(b.nvim.command("startinsert",!0),a.sendText(`${o} install --production --ignore-scripts --no-lockfile`,!0))}),this.addMultipleAction("uninstall",async t=>{let i=[];for(let n of t)n.data.isLocal||i.push(n.data.id);ge.uninstallExtension(i).catch(n=>{qye.error(n)})})}async loadItems(e){let t=[],i=await ge.getExtensionStates(),n=await ge.getLockedList();for(let o of i){let s="+";o.state=="disabled"?s="-":o.state=="activated"?s="*":o.state=="unknown"&&(s="?");let a=await this.nvim.call("resolve",o.root),l=n.includes(o.id);t.push({label:[`${s} ${o.id}${l?" \uE0A2":""}`,...o.isLocal?["[RTP]"]:[],o.version,a.replace(bz.default.homedir(),"~")],filterText:o.id,data:{id:o.id,root:a,state:o.state,isLocal:o.isLocal,priority:$ye(o.state)}})}return t.sort((o,s)=>o.data.priority!=s.data.priority?s.data.priority-o.data.priority:s.data.id-o.data.id?1:-1),$r(this.alignColumns,t)}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocExtensionsActivited /\\v^\\*/ contained containedin=CocExtensionsLine",!0),e.command("syntax match CocExtensionsLoaded /\\v^\\+/ contained containedin=CocExtensionsLine",!0),e.command("syntax match CocExtensionsDisabled /\\v^-/ contained containedin=CocExtensionsLine",!0),e.command("syntax match CocExtensionsName /\\v%3c\\S+/ contained containedin=CocExtensionsLine",!0),e.command("syntax match CocExtensionsRoot /\\v\\t[^\\t]*$/ contained containedin=CocExtensionsLine",!0),e.command("syntax match CocExtensionsLocal /\\v\\[RTP\\]/ contained containedin=CocExtensionsLine",!0),e.command("highlight default link CocExtensionsActivited Special",!0),e.command("highlight default link CocExtensionsLoaded Normal",!0),e.command("highlight default link CocExtensionsDisabled Comment",!0),e.command("highlight default link CocExtensionsName String",!0),e.command("highlight default link CocExtensionsLocal MoreMsg",!0),e.command("highlight default link CocExtensionsRoot Comment",!0),e.resumeNotification().catch(t=>{})}},wz=EC;function $ye(r){switch(r){case"unknown":return 2;case"activated":return 1;case"disabled":return-1;default:return 0}}var xz=S(require("path"));var Dz=S($i());var CC=class extends Mt{constructor(e){super(e);this.defaultAction="edit";this.description="list of current workspace folders";this.name="folders";this.addAction("edit",async t=>{let i=await e.call("input",["Folder: ",t.label,"dir"]),n=await Ht(i);if(!n||!n.isDirectory()){C.showMessage(`invalid path: ${i}`,"error");return}b.renameWorkspaceFolder(t.label,i)}),this.addAction("delete",async t=>{b.removeWorkspaceFolder(t.label)},{reload:!0,persist:!0}),this.addAction("newfile",async t=>{let i=await C.requestInput("File name",t.label+"/"),n=xz.default.dirname(i),o=await Ht(n);(!o||!o.isDirectory())&&Dz.default.mkdirpSync(n),await b.createFile(i,{overwrite:!1,ignoreIfExists:!0}),await this.jumpTo($.file(i).toString())})}async loadItems(e){return b.folderPaths.map(t=>({label:t}))}},Sz=CC;var Ez=S(require("path"));var _C=S(jn());var PC=class extends Mt{constructor(e){super(e);this.defaultAction="open";this.description="links of current buffer";this.name="links";this.addAction("open",async t=>{let{target:i}=t.data;$.parse(i).scheme.startsWith("http")?await e.call("coc#util#open_url",i):await b.jumpTo(i)}),this.addAction("jump",async t=>{let{location:i}=t.data;await b.jumpTo(i.uri,i.range.start)})}async loadItems(e,t){let i=await e.window.buffer,n=b.getDocument(i.id);if(!n)return null;let o=[],s=await U.getDocumentLinks(n.textDocument,t);if(s==null)throw new Error("Links provider not found.");let a=[];for(let l of s)l.target?o.push({label:Cz(l.target),data:{target:l.target,location:_C.Location.create(n.uri,l.range)}}):(l=await U.resolveDocumentLink(l),l.target&&o.push({label:Cz(l.target),data:{target:l.target,location:_C.Location.create(n.uri,l.range)}}),a.push(l));return o}},_z=PC;function Cz(r){if(!r.startsWith("file:"))return r;let e=$.parse(r).fsPath;return Ye(b.cwd,e)?Ez.default.relative(b.cwd,e):e}var TC=class extends Mt{constructor(e,t){super(e);this.listMap=t;this.name="lists";this.defaultAction="open";this.description="registered lists of coc.nvim";this.mru=new Gl("lists");this.addAction("open",async i=>{let{name:n}=i.data;await this.mru.add(n),await e.command(`CocList ${n}`)})}async loadItems(e){let t=[],i=await this.mru.load();for(let n of this.listMap.values())n.name!="lists"&&t.push({label:[n.name,...n.description?[n.description]:[]],data:{name:n.name,interactive:n.interactive,score:Bye(i,n.name)}});return t.sort((n,o)=>o.data.score-n.data.score),$r(this.alignColumns,t)}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocListsDesc /\\t.*$/ contained containedin=CocListsLine",!0),e.command("highlight default link CocListsDesc Comment",!0),e.resumeNotification().catch(t=>{})}},Pz=TC;function Bye(r,e){let t=r.indexOf(e);return t==-1?-1:r.length-t}var Tz=S(require("path")),Yp=S(jn());var Rz=S(El());var Je=S(W());function _n(r){switch(r){case Je.SymbolKind.File:return"File";case Je.SymbolKind.Module:return"Module";case Je.SymbolKind.Namespace:return"Namespace";case Je.SymbolKind.Package:return"Package";case Je.SymbolKind.Class:return"Class";case Je.SymbolKind.Method:return"Method";case Je.SymbolKind.Property:return"Property";case Je.SymbolKind.Field:return"Field";case Je.SymbolKind.Constructor:return"Constructor";case Je.SymbolKind.Enum:return"Enum";case Je.SymbolKind.Interface:return"Interface";case Je.SymbolKind.Function:return"Function";case Je.SymbolKind.Variable:return"Variable";case Je.SymbolKind.Constant:return"Constant";case Je.SymbolKind.String:return"String";case Je.SymbolKind.Number:return"Number";case Je.SymbolKind.Boolean:return"Boolean";case Je.SymbolKind.Array:return"Array";case Je.SymbolKind.Object:return"Object";case Je.SymbolKind.Key:return"Key";case Je.SymbolKind.Null:return"Null";case Je.SymbolKind.EnumMember:return"EnumMember";case Je.SymbolKind.Struct:return"Struct";case Je.SymbolKind.Event:return"Event";case Je.SymbolKind.Operator:return"Operator";case Je.SymbolKind.TypeParameter:return"TypeParameter";default:return"Unknown"}}var jWe=j()("list-symbols");function kz(r,e){return`${r.name}${e?` ${e}`:""}`}var RC=class extends ls{constructor(){super(...arguments);this.description="symbols of current document";this.name="outline";this.options=[{name:"-k, -kind KIND",hasValue:!0,description:"filters also by kind"}]}async loadItems(e,t){let i=await e.window.buffer,n=b.getDocument(i.id);if(!n)return null;let s=this.getConfig().get("ctagsFilestypes",[]),a,l=this.parseArguments(e.args);if(s.includes(n.filetype)||(a=await U.getDocumentSymbol(n.textDocument,t)),t.isCancellationRequested)return[];if(!a)return await this.loadCtagsSymbols(n);if(a.length==0)return[];let u=l.kind?l.kind.toLowerCase():null,c=[];if(!a[0].hasOwnProperty("location")){function p(d,h=0){d.sort(jye);for(let m of d){let y=_n(m.kind),v=Yp.Location.create(n.uri,m.selectionRange);c.push({label:[`${"| ".repeat(h)}${m.name}`,`[${y}]`,`${m.range.start.line+1}`],filterText:kz(m,l.kind==""?y:null),location:v,data:{kind:y}}),m.children&&m.children.length&&p(m.children,h+1)}}p(a),u&&(c=c.filter(d=>d.data.kind.toLowerCase().indexOf(u)==0))}else{a.sort((d,h)=>{let m=d.location.range.start,y=h.location.range.start,v=m.line-y.line;return v==0?m.character-y.character:v});for(let d of a){let h=_n(d.kind);d.name.endsWith(") callback")||u&&!h.toLowerCase().startsWith(u)||(d.location.uri===void 0&&(d.location.uri=n.uri),c.push({label:[d.name,`[${h}]`,`${d.location.range.start.line+1}`],filterText:kz(d,l.kind==""?h:null),location:d.location}))}}return $r(this.alignColumns,c)}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocOutlineName /\\v\\s?[^\\t]+\\s/ contained containedin=CocOutlineLine",!0),e.command("syntax match CocOutlineIndentLine /\\v\\|/ contained containedin=CocOutlineLine,CocOutlineName",!0),e.command("syntax match CocOutlineKind /\\[\\w\\+\\]/ contained containedin=CocOutlineLine",!0),e.command("syntax match CocOutlineLine /\\d\\+$/ contained containedin=CocOutlineLine",!0),e.command("highlight default link CocOutlineName Normal",!0),e.command("highlight default link CocOutlineIndentLine Comment",!0),e.command("highlight default link CocOutlineKind Typedef",!0),e.command("highlight default link CocOutlineLine Comment",!0),e.resumeNotification(!1,!0).logError()}async loadCtagsSymbols(e){if(!Rz.default.sync("ctags",{nothrow:!0}))return[];let t=$.parse(e.uri),i=Tz.default.extname(t.fsPath),n="",s=`${await this.nvim.call("tempname")}.${i}`,a=await this.nvim.call("fnameescape",s);await Z3(a,e.getDocumentContent());try{n=await hn(`ctags -f - --excmd=number --language-force=${e.filetype} ${a}`)}catch(c){}if(n.trim().length||(n=await hn(`ctags -f - --excmd=number ${a}`)),n=n.trim(),!n)return[];let l=n.split(/\r?\n/),u=[];for(let c of l){let f=c.split(" ");if(f.length<4)continue;let p=Number(f[2].replace(/;"$/,"")),d=e.getline(p-1);if(!d)continue;let h=d.indexOf(f[0]),m=h==-1?0:h,y=Yp.Range.create(p-1,m,p-1,m+f[0].length);u.push({label:`${f[0]} [${f[3]}] ${p}`,filterText:f[0],location:Yp.Location.create(e.uri,y),data:{line:p}})}return u.sort((c,f)=>c.data.line-f.data.line),u}},Iz=RC;function jye(r,e){let t=r.selectionRange,i=e.selectionRange;return t.start.line!=i.start.line?t.start.line-i.start.line:t.start.character-i.start.character}var kC=class extends Mt{constructor(e){super(e);this.defaultAction="toggle";this.description="registered services of coc.nvim";this.name="services";this.addAction("toggle",async t=>{let{id:i}=t.data;await Vt.toggle(i),await He(100)},{persist:!0,reload:!0})}async loadItems(e){let t=Vt.getServiceStats();return t.sort((i,n)=>i.id>n.id?-1:1),$r(this.alignColumns,t.map(i=>({label:[i.state=="running"?"*":" ",i.id,`[${i.state}]`,i.languageIds.join(", ")],data:{id:i.id}})))}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocServicesPrefix /\\v^./ contained containedin=CocServicesLine",!0),e.command("syntax match CocServicesName /\\v%3c\\S+/ contained containedin=CocServicesLine",!0),e.command("syntax match CocServicesStat /\\v\\t\\[\\w+\\]/ contained containedin=CocServicesLine",!0),e.command("syntax match CocServicesLanguages /\\v(\\])@<=.*$/ contained containedin=CocServicesLine",!0),e.command("highlight default link CocServicesPrefix Special",!0),e.command("highlight default link CocServicesName Type",!0),e.command("highlight default link CocServicesStat Statement",!0),e.command("highlight default link CocServicesLanguages Comment",!0),e.resumeNotification().catch(t=>{})}},Fz=kC;var Av=S(jn());var ZWe=j()("list-sources"),IC=class extends Mt{constructor(e){super(e);this.defaultAction="toggle";this.description="registered completion sources";this.name="sources";this.addAction("toggle",async t=>{let{name:i}=t.data;Ze.toggleSource(i)},{persist:!0,reload:!0}),this.addAction("refresh",async t=>{let{name:i}=t.data;await Ze.refresh(i)},{persist:!0,reload:!0}),this.addAction("open",async t=>{let{location:i}=t;i&&await this.jumpTo(i)})}async loadItems(e){let t=Ze.sourceStats(),i=await e.buffer.getOption("filetype"),n=b.env.disabledSources,o=n?n[i]||[]:[];return t.sort((s,a)=>s.type!=a.type?s.typea.name?-1:1),t.map(s=>{let a=s.disabled?" ":"*";o&&o.includes(s.name)&&(a="-");let l;return s.filepath&&(l=Av.Location.create($.file(s.filepath).toString(),Av.Range.create(0,0,0,0))),{label:`${a} ${Ov(s.name,22)} ${Ov("["+s.shortcut+"]",10)} ${Ov(s.triggerCharacters.join(""),10)} ${Ov(s.priority.toString(),3)} ${s.filetypes.join(",")}`,location:l,data:{name:s.name}}})}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocSourcesPrefix /\\v^./ contained containedin=CocSourcesLine",!0),e.command("syntax match CocSourcesName /\\v%3c\\S+/ contained containedin=CocSourcesLine",!0),e.command("syntax match CocSourcesType /\\v%25v.*%36v/ contained containedin=CocSourcesLine",!0),e.command("syntax match CocSourcesPriority /\\v%46v.*%50v/ contained containedin=CocSourcesLine",!0),e.command("syntax match CocSourcesFileTypes /\\v\\S+$/ contained containedin=CocSourcesLine",!0),e.command("highlight default link CocSourcesPrefix Special",!0),e.command("highlight default link CocSourcesName Type",!0),e.command("highlight default link CocSourcesPriority Number",!0),e.command("highlight default link CocSourcesFileTypes Comment",!0),e.command("highlight default link CocSourcesType Statement",!0),e.resumeNotification(!1,!0)}},Az=IC;function Ov(r,e){return r.length>e?r.slice(0,e-1)+".":r+" ".repeat(e-r.length)}var FC=S(require("path")),Oz=S(Qs());var Lz=S(W());var f5e=j()("list-symbols"),AC=class extends ls{constructor(){super(...arguments);this.interactive=!0;this.description="search workspace symbols";this.detail="Symbols list is provided by server, it works on interactive mode only.";this.name="symbols";this.options=[{name:"-k, -kind KIND",description:"Filter symbols by kind.",hasValue:!0}]}async loadItems(e,t){let{input:i}=e,n=this.parseArguments(e.args),o=n.kind?n.kind.toLowerCase():"";if(!e.options.interactive)throw new Error("Symbols only works on interactive mode");let s=await U.getWorkspaceSymbols(i,t);if(!s)throw new Error("No workspace symbols provider registed");let l=this.getConfig().get("excludes",[]),u=[];for(let c of s){let f=_n(c.kind);if(o&&f.toLowerCase()!=o)continue;let p=$.parse(c.location.uri).fsPath;Ye(b.cwd,p)&&(p=FC.default.relative(b.cwd,p)),!l.some(d=>Oz.default(p,d))&&u.push({label:[c.name,`[${f}]`,p],filterText:`${c.name}`,location:c.location,data:{original:c,kind:c.kind,file:p,score:Tv(i,c.name)}})}return u.sort((c,f)=>c.data.score!=f.data.score?f.data.score-c.data.score:c.data.kind!=f.data.kind?c.data.kind-f.data.kind:c.data.file.length-f.data.file.length),$r(this.alignColumns,u)}async resolveItem(e){let t=e.data.original;if(!t)return null;let i=new Lz.CancellationTokenSource,n=await U.resolveWorkspaceSymbol(t,i.token);if(!n)return null;let o=_n(n.kind),s=$.parse(n.location.uri).fsPath;return Ye(b.cwd,s)&&(s=FC.default.relative(b.cwd,s)),{label:`${t.name} [${o}] ${s}`,filterText:`${t.name}`,location:t.location}}doHighlight(){let{nvim:e}=this;e.pauseNotification(),e.command("syntax match CocSymbolsName /\\v^\\s*\\S+/ contained containedin=CocSymbolsLine",!0),e.command("syntax match CocSymbolsKind /\\[\\w\\+\\]\\s*\\t/ contained containedin=CocSymbolsLine",!0),e.command("syntax match CocSymbolsFile /\\S\\+$/ contained containedin=CocSymbolsLine",!0),e.command("highlight default link CocSymbolsName Normal",!0),e.command("highlight default link CocSymbolsKind Typedef",!0),e.command("highlight default link CocSymbolsFile Comment",!0),e.resumeNotification().catch(t=>{})}},Mz=AC;var qz=j()("list-manager"),$z=["","","","<2-LeftMouse>"],Bz=class{constructor(){this.plugTs=0;this.sessionsMap=new Map;this.disposables=[];this.listMap=new Map}init(e){this.nvim=e,this.config=new Pv,this.prompt=new JH(e,this.config),this.mappings=new VH(this,e,this.config);let t=this.config.get("selectedSignText","*");e.command(`sign define CocSelected text=${t} texthl=CocSelectedText linehl=CocSelectedLine`,!0),A.on("InputChar",this.onInputChar,this,this.disposables),A.on("FocusGained",Nz.default(async()=>{await this.getCurrentSession()&&this.prompt.drawPrompt()},100),null,this.disposables);let i;A.on("WinEnter",n=>{let o=this.getSessionByWinid(n);o&&this.prompt.start(o.listOptions)},null,this.disposables),A.on("WinLeave",n=>{this.getSessionByWinid(n)&&this.prompt.cancel()}),this.disposables.push(Xp.Disposable.create(()=>{i&&clearTimeout(i)})),this.prompt.onDidChangeInput(()=>{let{session:n}=this;!n||(n.onInputChange(),n.history.filter())}),this.registerList(new _z(e)),this.registerList(new ls(e)),this.registerList(new Mz(e)),this.registerList(new Iz(e)),this.registerList(new gz(e)),this.registerList(new wz(e)),this.registerList(new yz(e)),this.registerList(new Az(e)),this.registerList(new Fz(e)),this.registerList(new Pz(e,this.listMap)),this.registerList(new Sz(e))}async start(e){let t=this.parseArgs(e);if(!t)return;let{name:i}=t.list,n=this.sessionsMap.get(i);n&&n.dispose(),this.prompt.start(t.options);let o=new lz(this.nvim,this.prompt,t.list,t.options,t.listArgs,this.config);this.sessionsMap.set(i,o),this.lastSession=o;try{await o.start(e)}catch(s){this.nvim.call("coc#prompt#stop_prompt",["list"],!0);let a=s instanceof Error?s.message:s.toString();C.showMessage(`Error on "CocList ${i}": ${a}`,"error"),qz.error(s)}}getSessionByWinid(e){for(let t of this.sessionsMap.values())if(t&&t.winid==e)return this.lastSession=t,t;return null}async getCurrentSession(){let{id:e}=await this.nvim.window;for(let t of this.sessionsMap.values())if(t&&t.winid==e)return this.lastSession=t,t;return null}async resume(e){var t;if(!e)await((t=this.session)==null?void 0:t.resume());else{let i=this.sessionsMap.get(e);if(!i){C.showMessage(`Can't find exists ${e} list`);return}await i.resume()}}async doAction(e){let t=this.lastSession;!t||await t.doAction(e)}async first(e){let t=this.getSession(e);t&&await t.first()}async last(e){let t=this.getSession(e);t&&await t.last()}async previous(e){let t=this.getSession(e);t&&await t.previous()}async next(e){let t=this.getSession(e);t&&await t.next()}getSession(e){return e?this.sessionsMap.get(e):this.session}async cancel(e=!0){this.prompt.cancel(),!!e&&this.session&&await this.session.hide()}reset(){this.prompt.cancel(),this.lastSession=void 0;for(let e of this.sessionsMap.values())e.dispose();this.sessionsMap.clear(),this.nvim.call("coc#prompt#stop_prompt",["list"],!0)}switchMatcher(){var e;(e=this.session)==null||e.switchMatcher()}async togglePreview(){let{nvim:e}=this,t=await e.call("coc#list#get_preview",[0]);t!=-1?(await e.createWindow(t).close(!0),await e.command("redraw")):await this.doAction("preview")}async chooseAction(){let{lastSession:e}=this;e&&await e.chooseAction()}parseArgs(e){let t=[],i=!1,n=!1,o=!1,s=!1,a=!1,l,u="",c="fuzzy",f="bottom",p=[],d=[];for(let y of e)if(!l&&y.startsWith("-"))d.push(y);else if(l)p.push(y);else{if(!/^\w+$/.test(y))return C.showMessage(`Invalid list option: "${y}"`,"error"),null;l=y}l=l||"lists";let h=b.getConfiguration(`list.source.${l}`);!d.length&&!p.length&&(d=h.get("defaultOptions",[])),p.length||(p=h.get("defaultArgs",[]));for(let y of d)if(y.startsWith("--input"))u=y.slice(8);else if(y=="--number-select"||y=="-N")o=!0;else if(y=="--auto-preview"||y=="-A")n=!0;else if(y=="--regex"||y=="-R")c="regex";else if(y=="--strict"||y=="-S")c="strict";else if(y=="--interactive"||y=="-I")i=!0;else if(y=="--top")f="top";else if(y=="--tab")f="tab";else if(y=="--ignore-case"||y=="--normal"||y=="--no-sort")t.push(y.slice(2));else if(y=="--first")a=!0;else if(y=="--no-quit")s=!0;else return C.showMessage(`Invalid option "${y}" of list`,"error"),null;let m=this.listMap.get(l);return m?i&&!m.interactive?(C.showMessage(`Interactive mode of "${l}" list not supported`,"error"),null):{list:m,listArgs:p,options:{numberSelect:o,autoPreview:n,noQuit:s,first:a,input:u,interactive:i,matcher:c,position:f,ignorecase:!!t.includes("ignore-case"),mode:t.includes("normal")?"normal":"insert",sort:!t.includes("no-sort")}}:(C.showMessage(`List ${l} not found`,"error"),null)}async onInputChar(e,t,i){if(e!="list")return;let{mode:n}=this.prompt,o=Date.now();if(t==""||this.plugTs&&o-this.plugTs<20){this.plugTs=o;return}if(!!t){if(t==""){await this.cancel();return}try{n=="insert"?await this.onInsertInput(t,i):await this.onNormalInput(t,i)}catch(s){C.showMessage(`Error on input ${t}: ${s}`),qz.error(s)}}}async onInsertInput(e,t){let{session:i}=this;if(!i)return;if($z.includes(e)){await this.onMouseEvent(e);return}if(!(await i.doNumberSelect(e)||await this.mappings.doInsertKeymap(e)||t)&&!(e.startsWith("<")&&e.endsWith(">")))for(let s of e){let a=s.codePointAt(0);if(a==65533||a<32||a>=127&&a<=159)return;await this.prompt.acceptCharacter(s)}}async onNormalInput(e,t){if($z.includes(e)){await this.onMouseEvent(e);return}await this.mappings.doNormalKeymap(e)||await this.feedkeys(e)}onMouseEvent(e){if(this.session)return this.session.onMouseEvent(e)}async feedkeys(e,t=!0){let{nvim:i}=this;e=e.startsWith("<")&&e.endsWith(">")?`\\${e}`:e,await i.call("coc#prompt#stop_prompt",["list"]),await i.call("eval",[`feedkeys("${e}", "${t?"i":"in"}")`]),this.prompt.start()}async command(e){let{nvim:t}=this;await t.call("coc#prompt#stop_prompt",["list"]),await t.command(e),this.prompt.start()}async normal(e,t=!0){let{nvim:i}=this;await i.call("coc#prompt#stop_prompt",["list"]),await i.command(`normal${t?"!":""} ${e}`),this.prompt.start()}async call(e){if(this.session)return await this.session.call(e)}get session(){return this.lastSession}registerList(e){let{name:t}=e,i=this.listMap.get(t);return this.listMap.has(t)&&(i&&(typeof i.dispose=="function"&&i.dispose(),this.listMap.delete(t)),C.showMessage(`list "${t}" recreated.`)),this.listMap.set(t,e),ge.addSchemeProperty(`list.source.${t}.defaultOptions`,{type:"array",default:e.interactive?["--interactive"]:[],description:`Default list options of "${t}" list, only used when both list option and argument are empty.`,uniqueItems:!0,items:{type:"string",enum:["--top","--normal","--no-sort","--input","--tab","--strict","--regex","--ignore-case","--number-select","--interactive","--auto-preview","--first","--no-quit"]}}),ge.addSchemeProperty(`list.source.${t}.defaultArgs`,{type:"array",default:[],description:`Default argument list of "${t}" list, only used when list argument is empty.`,uniqueItems:!0,items:{type:"string"}}),Xp.Disposable.create(()=>{typeof e.dispose=="function"&&e.dispose(),this.listMap.delete(t)})}get names(){return Array.from(this.listMap.keys())}get descriptions(){let e={};for(let t of this.listMap.keys()){let i=this.listMap.get(t);e[t]=i.description}return e}async loadItems(e){let t=[e],i=this.parseArgs(t);if(!i)return;let{list:n,options:o,listArgs:s}=i,l=new Xp.CancellationTokenSource().token,u=await this.nvim.eval('[win_getid(),bufnr("%")]');return await n.loadItems({options:o,args:s,input:"",cwd:b.cwd,window:this.nvim.createWindow(u[0]),buffer:this.nvim.createBuffer(u[1]),listWindow:null},l)}toggleMode(){let e=this.lastSession;e&&e.toggleMode()}get isActivated(){var e;return((e=this.session)==null?void 0:e.winid)!=null}stop(){let e=this.lastSession;e&&e.stop()}dispose(){for(let e of this.sessionsMap.values())e.dispose();this.sessionsMap.clear(),this.config&&this.config.dispose(),this.lastSession=void 0,z(this.disposables)}},Kt=new Bz;function zye(){let r=e=>e==="coc.nvim"?Uz():this.require(e);return r.resolve=e=>Pn._resolveFilename(e,this),r.main=process.mainModule,r.extensions=Pn._extensions,r.cache=Pn._cache,r}function Gye(r){return function(e,t){let i=zye.call(this),n=Hz.dirname(t),o=e.replace(/^\#\!.*/,""),s=Pn.wrap(o),a=Lv.runInContext(s,r,{filename:t}),l=[this.exports,i,this,t,n];return a.apply(this.exports,l)}}function Vye(r,e){let t=new Pn(r);t.paths=Pn._nodeModulePaths(r);let i=Lv.createContext({module:t,Buffer,console:{debug:(...n)=>{e.debug.apply(e,n)},log:(...n)=>{e.debug.apply(e,n)},error:(...n)=>{e.error.apply(e,n)},info:(...n)=>{e.info.apply(e,n)},warn:(...n)=>{e.warn.apply(e,n)}}});J5(i,global),i.Reflect=Reflect,i.require=function(o){let s=Pn.prototype._compile;Pn.prototype._compile=Gye(i);let a=i.module.require(o);return Pn.prototype._compile=s,a},i.process=new process.constructor;for(let n of Object.keys(process))i.process[n]=process[n];return Wye.forEach(n=>{i.process[n]=Hye(n)}),i.process.chdir=()=>{},i.process.umask=n=>{if(typeof n!="undefined")throw new Error("Cannot use process.umask() to change mask (read-only)");return process.umask()},i}function Gz(r,e,t=!1){if(t||!Wz.default.existsSync(e))return{activate:()=>{},deactivate:null};let i=Vye(e,zz(`extension:${r}`));delete Pn._cache[require.resolve(e)];let n=i.require(e),o=n&&n.activate||n;return typeof o!="function"?{activate:()=>{},deactivate:null}:{activate:o,deactivate:typeof n.deactivate=="function"?n.deactivate:null}}var Xz=j(),Sr=Xz("extensions"),Zz=class{constructor(){this.extensions=new Map;this.disabled=new Set;this._onDidLoadExtension=new Mv.Emitter;this._onDidActiveExtension=new Mv.Emitter;this._onDidUnloadExtension=new Mv.Emitter;this._additionalSchemes={};this.activated=!1;this.disposables=[];this.ready=!0;this.onDidLoadExtension=this._onDidLoadExtension.event;this.onDidActiveExtension=this._onDidActiveExtension.event;this.onDidUnloadExtension=this._onDidUnloadExtension.event;let e=global.hasOwnProperty("__TEST__")?Fe.default.join(__dirname,"__tests__"):process.env.COC_DATA_HOME,t=this.root=Fe.default.join(e,"extensions");st.default.existsSync(t)||st.default.mkdirpSync(t);let i=Fe.default.join(t,"package.json");st.default.existsSync(i)||st.default.writeFileSync(i,'{"dependencies":{}}',"utf8");let n=Fe.default.join(t,"db.json");this.db=new Ym(n)}get outputChannel(){return this._outputChannel?this._outputChannel:(this._outputChannel=C.createOutputChannel("extensions"),this._outputChannel)}async init(){let e=this.db.fetch("extension")||{},t=Object.keys(e);for(let o of t)e[o].disabled==!0&&this.disabled.add(o);if(process.env.COC_NO_PLUGINS)return;let i=await this.globalExtensionStats(),n=await this.localExtensionStats(i.map(o=>o.id));i=i.concat(n),this.memos=new V5(Fe.default.resolve(this.root,"../memos.json")),i.map(o=>{let s=o.isLocal?Jr.Local:Jr.Global;try{this.createExtension(o.root,o.packageJSON,s)}catch(a){Sr.error(`Error on create ${o.root}:`,a)}}),await this.loadFileExtensions(),me.register({id:"extensions.forceUpdateAll",execute:async()=>{let o=await this.cleanExtensions();Sr.info(`Force update extensions: ${o}`),await this.installExtensions(o)}},!1,"remove all global extensions and install them"),b.onDidRuntimePathChange(async o=>{for(let s of o)s&&this.checkDirectory(s)===!0&&await this.loadExtension(s)},null,this.disposables)}async activateExtensions(){this.activated=!0;for(let o of this.extensions.values()){let{id:s,packageJSON:a}=o.extension;await this.setupActiveEvents(s,a)}let e=new mn(b.nvim);if(A.on("CursorMoved",Vz.debounce(async o=>{if(this.installBuffer&&o==this.installBuffer.bufnr){let s=await b.nvim.call("line",["."]),a=this.installBuffer.getMessages(s-1),l=a&&a.length?[{content:a.join(` +`),filetype:"txt"}]:[];await e.show(l,{modes:["n"]})}},500)),global.hasOwnProperty("__TEST__"))return;this.checkExtensions().logError();let t=b.getConfiguration("coc.preferences"),i=t.get("extensionUpdateCheck","never"),n=t.get("silentAutoupdate",!0);if(i!="never"){let o=new Date,s=new Date(o.getFullYear(),o.getMonth(),o.getDate()-(i=="daily"?0:7)),a=this.db.fetch("lastUpdate");if(a&&Number(a)>s.getTime())return;this.outputChannel.appendLine("Start auto update..."),this.updateExtensions(!1,n).logError()}}async updateExtensions(e,t=!1){if(!this.npm)return;let i=await this.getLockedList(),n=await this.globalExtensionStats();n=n.filter(l=>![...i,...this.disabled].includes(l.id)),this.db.push("lastUpdate",Date.now()),t&&C.showMessage("Updating extensions, checkout output:///extensions for details.","more");let o=this.installBuffer=new R0(!0,e,t?this.outputChannel:void 0);o.setExtensions(n.map(l=>l.id)),await o.show(b.nvim);let s=dv(this.npm,this.modulesFolder);await vf(n,l=>{let{id:u}=l;o.startProgress([u]);let c=l.exotic?l.uri:null,f=s(u);return f.on("message",(p,d)=>{o.addMessage(u,p,d)}),f.update(c).then(p=>{o.finishProgress(u,!0),p&&this.loadExtension(p).logError()},p=>{o.addMessage(u,p.message),o.finishProgress(u,!1)})},t?1:3)}async checkExtensions(){let{globalExtensions:e}=b.env;if(e&&e.length){let t=this.filterGlobalExtensions(e);this.installExtensions(t).logError()}}get installer(){return dv(this.npm,this.modulesFolder)}async installExtensions(e=[]){let{npm:t}=this;if(!t||!e.length)return;e=eg(e);let i=this.installBuffer=new R0;i.setExtensions(e),await i.show(b.nvim);let n=dv(this.npm,this.modulesFolder);await vf(e,s=>{i.startProgress([s]);let a=n(s);return a.on("message",(l,u)=>{i.addMessage(s,l,u)}),a.install().then(l=>{i.finishProgress(s,!0);let u=Fe.default.join(this.modulesFolder,l);this.loadExtension(u).logError()},l=>{i.addMessage(s,l.message),i.finishProgress(s,!1),Sr.error(`Error on install ${s}`,l)})})}getMissingExtensions(){let e=this.loadJson()||{dependencies:{}},t=[];for(let i of Object.keys(e.dependencies)){let n=Fe.default.join(this.modulesFolder,i);if(!st.default.existsSync(n)){let o=e.dependencies[i];o.startsWith("http")?t.push(o):t.push(i)}}return t}get npm(){let e=b.getConfiguration("npm").get("binPath","npm");e=b.expand(e);for(let t of[e,"yarnpkg","yarn","npm"])try{return Yz.default.sync(t)}catch(i){continue}return C.showMessage("Can't find npm or yarn in your $PATH","error"),null}get all(){return Array.from(this.extensions.values()).map(e=>e.extension).filter(e=>!this.isDisabled(e.id))}getExtension(e){return this.extensions.get(e)}getExtensionState(e){if(this.isDisabled(e))return"disabled";let i=this.extensions.get(e);if(!i)return"unknown";let{extension:n}=i;return n.isActive?"activated":"loaded"}async getExtensionStates(){let e=await this.localExtensionStats([]),t=await this.globalExtensionStats();return e.concat(t.filter(i=>e.find(n=>n.id==i.id)==null))}async getLockedList(){let e=await this.db.fetch("extension");return e=e||{},Object.keys(e).filter(t=>e[t].locked===!0)}async toggleLock(e){let t=`extension.${e}.locked`;await this.db.fetch(t)?this.db.delete(t):this.db.push(t,!0)}async toggleExtension(e){let t=this.getExtensionState(e);if(t==null)return;t=="activated"&&await this.deactivate(e);let i=`extension.${e}.disabled`;if(this.db.push(i,t!="disabled"),t!="disabled")this.disabled.add(e),await this.unloadExtension(e);else{this.disabled.delete(e);let n=Fe.default.join(this.modulesFolder,e);st.default.existsSync(n)&&await this.loadExtension(n)}await He(200)}async reloadExtension(e){let t=this.extensions.get(e);if(!t){C.showMessage(`Extension ${e} not registered`,"error");return}if(t.type==Jr.Internal){C.showMessage(`Can't reload internal extension "${t.id}"`,"warning");return}t.type==Jr.SingleFile?await this.loadExtensionFile(t.filepath):t.directory?await this.loadExtension(t.directory):C.showMessage(`Can't reload extension ${t.id}`,"warning")}async cleanExtensions(){let e=this.modulesFolder;if(!st.default.existsSync(e))return[];let t=this.globalExtensions,i=[];for(let n of t){let o=Fe.default.join(e,n),s=await st.default.lstat(o);!s||s&&s.isSymbolicLink()||(await this.unloadExtension(n),await st.default.remove(o),i.push(n))}return i}async uninstallExtension(e){try{if(!e.length)return;let[t,i]=Qm(e,a=>this.globalExtensions.includes(a));i.length&&C.showMessage(`Extensions ${i} not global extensions, can't uninstall!`,"warning");let n=this.loadJson()||{dependencies:{}};for(let a of t){await this.unloadExtension(a),delete n.dependencies[a];let l=Fe.default.join(this.modulesFolder,a);st.default.existsSync(l)&&await st.default.remove(l)}let o={dependencies:{}};Object.keys(n.dependencies).sort().forEach(a=>{o.dependencies[a]=n.dependencies[a]});let s=Fe.default.join(this.root,"package.json");st.default.writeFileSync(s,JSON.stringify(o,null,2),{encoding:"utf8"}),C.showMessage(`Removed: ${t.join(" ")}`)}catch(t){C.showMessage(`Uninstall failed: ${t.message}`,"error")}}isDisabled(e){return this.disabled.has(e)}has(e){return this.extensions.has(e)}isActivated(e){let t=this.extensions.get(e);return!!(t&&t.extension.isActive)}async loadExtension(e){try{let t=Fe.default.dirname(e),i=Fe.default.normalize(t)!=Fe.default.normalize(this.modulesFolder),n=Fe.default.join(e,"package.json"),o=JSON.parse(st.default.readFileSync(n,"utf8")),{name:s}=o;return this.isDisabled(s)?!1:(await this.unloadExtension(s),this.createExtension(e,Object.freeze(o),i?Jr.Local:Jr.Global),!0)}catch(t){return C.showMessage(`Error on load extension from "${e}": ${t.message}`,"error"),Sr.error(`Error on load extension from ${e}`,t),!1}}async loadFileExtensions(){if(!process.env.COC_VIMCONFIG)return;let e=Fe.default.join(process.env.COC_VIMCONFIG,"coc-extensions");if(!st.default.existsSync(e))return;let t=await st.default.readdir(e);t=t.filter(i=>i.endsWith(".js"));for(let i of t)await this.loadExtensionFile(Fe.default.join(e,i))}loadedExtensions(){return Array.from(this.extensions.keys())}async watchExtension(e){let t=this.extensions.get(e);if(!t){C.showMessage(`extension ${e} not found`,"error");return}if(e.startsWith("single-"))C.showMessage(`watching ${t.filepath}`),this.disposables.push(Pl(t.filepath,async()=>{await this.loadExtensionFile(t.filepath),C.showMessage(`reloaded ${e}`)}));else{let i=b.getWatchmanPath();if(!i){C.showMessage("watchman not found","error");return}let n=await ta.createClient(i,t.directory);if(!n){C.showMessage("Can't create watchman client, check output:///watchman");return}C.showMessage(`watching ${t.directory}`),this.disposables.push(n),n.subscribe("**/*.js",async()=>{await this.reloadExtension(e),C.showMessage(`reloaded ${e}`)}).then(o=>{this.disposables.push(o)},o=>{Sr.error(o)})}}async loadExtensionFile(e){let t=Fe.default.basename(e),i="single-"+Fe.default.basename(e,".js");if(this.isDisabled(i))return;let n=Fe.default.dirname(e),o={name:i,main:t,engines:{coc:"^0.0.79"}};await this.unloadExtension(i),this.createExtension(n,o,Jr.SingleFile)}async activate(e){if(this.isDisabled(e))throw new Error(`Extension ${e} is disabled!`);let t=this.extensions.get(e);if(!t)throw new Error(`Extension ${e} not registered!`);let{extension:i}=t;return i.isActive?!0:(await Promise.resolve(i.activate()),i.isActive?(this._onDidActiveExtension.fire(i),!0):!1)}async deactivate(e){let t=this.extensions.get(e);return t?(await Promise.resolve(t.deactivate()),!0):!1}async call(e,t,i){let n=this.extensions.get(e);if(!n)throw new Error(`extension ${e} not registered`);let{extension:o}=n;o.isActive||await this.activate(e);let{exports:s}=o;if(!s||!s.hasOwnProperty(t))throw new Error(`method ${t} not found on extension ${e}`);return await Promise.resolve(s[t].apply(null,i))}getExtensionApi(e){let t=this.extensions.get(e);if(!t)return null;let{extension:i}=t;return i.isActive?i.exports:null}registerExtension(e,t){let{id:i,packageJSON:n}=e;this.extensions.set(i,{id:i,type:Jr.Internal,extension:e,deactivate:t,isLocal:!0});let{contributes:o}=n;if(o){let{configuration:s}=o;if(s&&s.properties){let{properties:a}=s,l={};for(let u of Object.keys(a)){let c=a[u].default;c!=null&&(l[u]=c)}b.configurations.extendsDefaults(l)}}this._onDidLoadExtension.fire(e),this.setupActiveEvents(i,n).logError()}get globalExtensions(){let e=this.loadJson();return!e||!e.dependencies?[]:Object.keys(e.dependencies)}async globalExtensionStats(){let e=this.loadJson();if(!e||!e.dependencies)return[];let{modulesFolder:t}=this;return(await Promise.all(Object.keys(e.dependencies).map(n=>new Promise(async o=>{try{let s=e.dependencies[n],a=Fe.default.join(t,n),l=this.checkDirectory(a);if(l instanceof Error)return C.showMessage(`Unable to load global extension at ${a}: ${l.message}`,"error"),Sr.error(`Error on load ${a}`,l),o(null);let u=await Yf(Fe.default.join(a,"package.json"),"utf8");a=await st.default.realpath(a);let c=JSON.parse(u),f=c&&c.version||"",p=c&&c.description||"",d=Kz.default.isValid(s)?s:"";o({id:n,isLocal:!1,version:f,description:p,exotic:/^https?:/.test(s),uri:d.replace(/\.git(#master)?$/,""),root:a,state:this.getExtensionState(n),packageJSON:Object.freeze(c)})}catch(s){Sr.error(s),o(null)}})))).filter(n=>n!=null)}async localExtensionStats(e){let i=(await b.nvim.eval("&runtimepath")).split(",");return(await Promise.all(i.map(o=>new Promise(async s=>{try{if(this.checkDirectory(o)!==!0)return s(null);let l=Fe.default.join(o,"package.json"),u=await Yf(l,"utf8"),c=JSON.parse(u),f=this.extensions.get(c.name);if(f&&!f.isLocal)return Sr.info(`Extension "${c.name}" in runtimepath already loaded.`),s(null);if(e.includes(c.name))return Sr.info(`Skipped load vim plugin from "${o}", "${c.name}" already global extension.`),s(null);let p=c&&c.version||"",d=c&&c.description||"";s({id:c.name,isLocal:!0,version:p,description:d,exotic:!1,root:o,state:this.getExtensionState(c.name),packageJSON:Object.freeze(c)})}catch(a){Sr.error(a),s(null)}})))).filter(o=>o!=null)}loadJson(){let{root:e}=this,t=Fe.default.join(e,"package.json");if(!st.default.existsSync(t))return null;let i=[],n=st.default.readFileSync(t,"utf8"),o=Ul(n,i,{allowTrailingComma:!0});return i&&i.length>0&&(C.showMessage(`Error on parse ${t}`,"error"),b.nvim.call("coc#util#open_file",["edit",t],!0)),o}get schemes(){return this._additionalSchemes}addSchemeProperty(e,t){this._additionalSchemes[e]=t,b.configurations.extendsDefaults({[e]:t.default})}async setupActiveEvents(e,t){let{activationEvents:i}=t;if(!this.canActivate(e))return;if(!i||Array.isArray(i)&&i.includes("*")){await this.activate(e).catch(s=>{C.showMessage(`Error on activate extension ${e}: ${s.message}`),this.outputChannel.appendLine(`Error on activate extension ${e}. +${s.message} + ${s.stack}`)});return}let n=[],o=()=>(z(n),new Promise(s=>{if(!this.canActivate(e))return this.outputChannel.appendLine(`Extension ${e} is disabled or not loaded.`),s();let a=setTimeout(()=>{this.outputChannel.appendLine(`Extension ${e} activate cost more than 1s`),s()},1e3);this.activate(e).then(()=>{clearTimeout(a),s()},l=>{clearTimeout(a),C.showMessage(`Error on activate extension ${e}: ${l.message}`),this.outputChannel.appendLine(`Error on activate extension ${e}:${l.message} + ${l.stack}`),s()})}));for(let s of i){let a=s.split(":"),l=a[0];if(l=="onLanguage"){if(b.filetypes.has(a[1])){await o();return}b.onDidOpenTextDocument(u=>{u.languageId==a[1]&&o()},null,n)}else if(l=="onCommand")me.onCommandList.push(a[1]),A.on("Command",async u=>{u==a[1]&&(await o(),await He(500))},null,n);else if(l=="workspaceContains"){let u=async()=>{let f=b.workspaceFolders.map(p=>$.parse(p.uri).fsPath);for(let p of f)if(Bo(p,a[1].split(/\s+/)))return await o(),!0};if(await u())return;b.onDidChangeWorkspaceFolders(u,null,n)}else if(l=="onFileSystem"){for(let u of b.documents)if($.parse(u.uri).scheme==a[1]){await o();return}b.onDidOpenTextDocument(u=>{$.parse(u.uri).scheme==a[1]&&o()},null,n)}else C.showMessage(`Unsupported event ${s} of ${e}`,"error")}}createExtension(e,t,i){let n=t.name,o=!1,s=null,a=Fe.default.join(e,t.main||"index.js"),l,u=[],c={activate:async()=>{if(o)return s;let p={subscriptions:u,extensionPath:e,globalState:this.memos.createMemento(`${n}|global`),workspaceState:this.memos.createMemento(`${n}|${b.rootPath}`),asAbsolutePath:d=>Fe.default.join(e,d),storagePath:Fe.default.join(this.root,`${n}-data`),logger:Xz(n)};if(o=!0,!l)try{let d=!(t.engines||{}).hasOwnProperty("coc");l=Gz(n,a,d)}catch(d){Sr.error(`Error on createExtension ${n} from ${a}`,d);return}try{s=await Promise.resolve(l.activate(p)),Sr.debug("activate:",n)}catch(d){o=!1,Sr.error(`Error on active extension ${n}: ${d.stack}`,d)}return s}};Object.defineProperties(c,{id:{get:()=>n,enumerable:!0},packageJSON:{get:()=>t,enumerable:!0},extensionPath:{get:()=>e,enumerable:!0},isActive:{get:()=>o,enumerable:!0},exports:{get:()=>s,enumerable:!0}}),this.extensions.set(n,{id:n,type:i,isLocal:i==Jr.Local,extension:c,directory:e,filepath:a,deactivate:()=>{if(!!o&&(o=!1,z(u),u.splice(0,u.length),u=[],l&&l.deactivate))try{return Promise.resolve(l.deactivate()).catch(p=>{Sr.error(`Error on ${n} deactivate: `,p)})}catch(p){Sr.error(`Error on ${n} deactivate: `,p)}}});let{contributes:f}=t;if(f){let{configuration:p,rootPatterns:d,commands:h}=f;if(p&&p.properties){let{properties:m}=p,y={};for(let v of Object.keys(m)){let x=m[v].default;x!=null&&(y[v]=x)}b.configurations.extendsDefaults(y)}if(d&&d.length)for(let m of d)b.addRootPattern(m.filetype,m.patterns);if(h&&h.length)for(let m of h)me.titles.set(m.command,m.title)}this._onDidLoadExtension.fire(c),this.activated&&this.setupActiveEvents(n,t).logError()}filterGlobalExtensions(e){e=e.map(s=>s.replace(/@.*$/,""));let t=e.filter(s=>!this.disabled.has(s));t=t.filter(s=>!this.extensions.has(s));let i=this.loadJson(),n=[],o=[];if(i&&i.dependencies)for(let s of Object.keys(i.dependencies)){let a=i.dependencies[s];typeof a=="string"&&st.default.existsSync(Fe.default.join(this.modulesFolder,s,"package.json"))&&(o.push(s),/^https?:/.test(a)&&n.push(a))}return t=t.filter(s=>/^https?:/.test(s)?!n.some(a=>a.startsWith(s)):!o.includes(s)),t}get modulesFolder(){return Fe.default.join(this.root,global.hasOwnProperty("__TEST__")?"":"node_modules")}canActivate(e){return!this.disabled.has(e)&&this.extensions.has(e)}async unloadExtension(e){this.extensions.get(e)&&(await this.deactivate(e),this.extensions.delete(e),this._onDidUnloadExtension.fire(e))}checkDirectory(e){try{let t=Fe.default.join(e,"package.json");if(!st.default.existsSync(t))throw new Error("package.json not found");let i=JSON.parse(st.default.readFileSync(t,"utf8")),{name:n,engines:o,main:s}=i;if(!n||!o)throw new Error("can't find name & engines in package.json");if(!o||!wt(o))throw new Error(`invalid engines in ${t}`);if(s&&!st.default.existsSync(Fe.default.join(e,s)))throw new Error(`main file ${s} not found, you may need to build the project.`);let a=Object.keys(o);if(!a.includes("coc")&&!a.includes("vscode"))throw new Error("Engines in package.json doesn't have coc or vscode");if(a.includes("coc")){let l=o.coc.replace(/^\^/,">=");if(!Jz.default.satisfies(b.version,l))throw new Error(`Please update coc.nvim, ${i.name} requires coc.nvim ${o.coc}`)}return!0}catch(t){return t}}dispose(){z(this.disposables)}},ge=new Zz;var K4e=j()("model-source"),OC=class{constructor(e){this._disabled=!1;this.nvim=b.nvim,this.name=e.name,this.filepath=e.filepath||"",this.sourceType=e.sourceType||Yr.Native,this.isSnippet=!!e.isSnippet,this.defaults=e}get priority(){return this.getConfig("priority",1)}get triggerOnly(){let e=this.defaults.triggerOnly;return typeof e=="boolean"?e:!this.triggerCharacters&&!this.triggerPatterns?!1:Array.isArray(this.triggerPatterns)&&this.triggerPatterns.length!=0}get triggerCharacters(){return this.getConfig("triggerCharacters",null)}get optionalFns(){return this.defaults.optionalFns||[]}get triggerPatterns(){let e=this.getConfig("triggerPatterns",null);return!e||e.length==0?null:e.map(t=>typeof t=="string"?new RegExp(t+"$"):t)}get shortcut(){let e=this.getConfig("shortcut","");return e||this.name.slice(0,3)}get enable(){return this._disabled?!1:this.getConfig("enable",!0)}get filetypes(){return this.getConfig("filetypes",null)}get disableSyntaxes(){return this.getConfig("disableSyntaxes",[])}getConfig(e,t){let i=b.getConfiguration(`coc.source.${this.name}`);return t=this.defaults.hasOwnProperty(e)?this.defaults[e]:t,i.get(e,t)}toggle(){this._disabled=!this._disabled}get firstMatch(){return this.getConfig("firstMatch",!0)}get menu(){let{shortcut:e}=this;return e?`[${e}]`:""}filterWords(e,t){let{firstMatch:i}=this,n=[],{input:o}=t,s=t.word;if(!o.length)return[];let a=o[0];for(let l of e)!l||l.length<3||i&&a!=l[0]||!i&&a.toLowerCase()!=l[0].toLowerCase()||l==s||l==o||n.push(l);return n}fixStartcol(e,t){let{col:i,input:n,line:o,bufnr:s}=e,a=Rt(o,0,i),l=b.getDocument(s);if(!l)return i;let{chars:u}=l;for(let c=a.length-1;c>=0;c--){let f=a[c];if(!u.isKeywordChar(f)&&!t.includes(f))break;n=`${f}${n}`,i=i-1}return e.col=i,e.input=n,i}async shouldComplete(e){let{disableSyntaxes:t}=this;if(e.synname&&t&&t.length){let n=(e.synname||"").toLowerCase();if(t.findIndex(o=>n.includes(o.toLowerCase()))!==-1)return!1}let i=this.defaults.shouldComplete;return i?await Promise.resolve(i.call(this,e)):!0}async refresh(){let e=this.defaults.refresh;e&&await Promise.resolve(e.call(this))}async onCompleteDone(e,t){let i=this.defaults.onCompleteDone;i&&await Promise.resolve(i.call(this,e,t))}async doComplete(e,t){let i=this.defaults.doComplete;return i?await Promise.resolve(i.call(this,e,t)):null}},Tn=OC;var tHe=j()("model-source-vim"),LC=class extends Tn{async callOptinalFunc(e,t){if(!this.optionalFns.includes(e))return null;let n=`coc#source#${this.name}#${e}`,o;try{o=await this.nvim.call(n,t)}catch(s){return C.showMessage(`Vim error from source ${this.name}: ${s.message}`,"error"),null}return o}async shouldComplete(e){return await super.shouldComplete(e)?this.optionalFns.includes("should_complete")?!!await this.callOptinalFunc("should_complete",[e]):!0:!1}async refresh(){await this.callOptinalFunc("refresh",[])}async onCompleteDone(e,t){await super.onCompleteDone(e,t),!!this.optionalFns.includes("on_complete")&&await this.callOptinalFunc("on_complete",[e])}onEnter(e){if(!this.optionalFns.includes("on_enter"))return;let t=b.getDocument(e);if(!t)return;let{filetypes:i}=this;i&&!i.includes(t.filetype)||this.callOptinalFunc("on_enter",[{bufnr:e,uri:t.uri,languageId:t.filetype}]).logError()}async doComplete(e,t){let{col:i,input:n,line:o,colnr:s}=e,a=await this.callOptinalFunc("get_startcol",[e]);if(t.isCancellationRequested)return;if(a){if(a<0)return null;a=Number(a),(isNaN(a)||a<0)&&(a=i),a!==i&&(n=Rt(o,a,s-1),e=Object.assign({},e,{col:a,changed:i-a,input:n}))}let l=await this.nvim.callAsync("coc#util#do_complete",[this.name,e]);if(!l||l.length==0||t.isCancellationRequested)return null;if(this.firstMatch&&n.length){let c=n[0];l=l.filter(f=>{let p=f.filterText?f.filterText[0]:f.word[0];return Vp(c,p)})}l=l.map(c=>{if(typeof c=="string")return{word:c,menu:this.menu,isSnippet:this.isSnippet};let f=c.menu?c.menu+" ":"";return c.menu=`${f}${this.menu}`,c.isSnippet=this.isSnippet,delete c.user_data,c});let u={items:l};return a&&(u.startcol=a),u}},Qz=LC;var obe=j()("sources"),p9=class{constructor(){this.sourceMap=new Map;this.disposables=[];this.remoteSourcePaths=[]}get nvim(){return b.nvim}createNativeSources(){try{this.disposables.push(t9().regist(this.sourceMap)),this.disposables.push(i9().regist(this.sourceMap)),this.disposables.push(a9().regist(this.sourceMap))}catch(e){console.error("Create source error:"+e.message)}}async createVimSourceExtension(e,t){let i=jv.default.basename(t,".vim");try{await e.command(`source ${t}`);let n=await e.call("coc#util#remote_fns",i);for(let c of["init","complete"])if(!n.includes(c))return C.showMessage(`${c} not found for source ${i}`,"error"),null;let o=await e.call(`coc#source#${i}#init`,[]),s={name:`coc-source-${i}`,engines:{coc:">= 0.0.1"},activationEvents:o.filetypes?o.filetypes.map(c=>`onLanguage:${c}`):["*"],contributes:{configuration:{properties:{[`coc.source.${i}.enable`]:{type:"boolean",default:!0},[`coc.source.${i}.firstMatch`]:{type:"boolean",default:!!o.firstMatch},[`coc.source.${i}.triggerCharacters`]:{type:"number",default:o.triggerCharacters||[]},[`coc.source.${i}.priority`]:{type:"number",default:o.priority||9},[`coc.source.${i}.shortcut`]:{type:"string",default:o.shortcut||i.slice(0,3).toUpperCase(),description:"Shortcut text shown in complete menu."},[`coc.source.${i}.disableSyntaxes`]:{type:"array",default:[],items:{type:"string"}},[`coc.source.${i}.filetypes`]:{type:"array",default:o.filetypes||null,description:"Enabled filetypes.",items:{type:"string"}}}}}},a=new Qz({name:i,filepath:t,sourceType:Yr.Remote,optionalFns:n.filter(c=>!["init","complete"].includes(c))}),l=!1,u={id:s.name,packageJSON:s,exports:void 0,extensionPath:t,activate:()=>(l=!0,this.addSource(a),Promise.resolve())};Object.defineProperty(u,"isActive",{get:()=>l}),ge.registerExtension(u,()=>{l=!1,this.removeSource(a)})}catch(n){C.showMessage(`Error on create vim source ${i}: ${n.message}`,"error")}}createRemoteSources(){let{runtimepath:e}=b.env,t=e.split(",");for(let i of t)this.createVimSources(i).logError()}async createVimSources(e){if(this.remoteSourcePaths.includes(e))return;this.remoteSourcePaths.push(e);let t=jv.default.join(e,"autoload/coc/source"),i=await Ht(t);if(i&&i.isDirectory()){let n=await c9.default.promisify(u9.default.readdir)(t);n=n.filter(s=>s.endsWith(".vim"));let o=n.map(s=>jv.default.join(t,s));if(o.length==0)return;await Promise.all(o.map(s=>this.createVimSourceExtension(this.nvim,s)))}}init(){this.createNativeSources(),this.createRemoteSources(),A.on("BufEnter",this.onDocumentEnter,this,this.disposables),b.watchOption("runtimepath",async(e,t)=>{let i=l9.default(e,t);for(let[n,o]of i)if(n==1){let s=o.replace(/,$/,"").split(",");for(let a of s)a&&await this.createVimSources(a)}},this.disposables)}get names(){return Array.from(this.sourceMap.keys())}get sources(){return Array.from(this.sourceMap.values())}has(e){return this.names.findIndex(t=>t==e)!=-1}getSource(e){return e&&this.sourceMap.get(e)||null}async doCompleteResolve(e,t){let i=this.getSource(e.source);if(i&&typeof i.onCompleteResolve=="function")try{await Promise.resolve(i.onCompleteResolve(e,t))}catch(n){obe.error("Error on complete resolve:",n.stack)}}async doCompleteDone(e,t){let i=JSON.parse(e.user_data),n=this.getSource(i.source);n&&typeof n.onCompleteDone=="function"&&await Promise.resolve(n.onCompleteDone(e,t))}shouldCommit(e,t){if(!e||!e.source)return!1;let i=this.getSource(e.source);return i&&i.sourceType==Yr.Service&&typeof i.shouldCommit=="function"?i.shouldCommit(e,t):!1}getCompleteSources(e){let{filetype:t}=e,i=Rt(e.line,0,e.colnr-1);return e.input==""&&!!e.triggerCharacter?this.getTriggerSources(i,t):this.getNormalSources(e.filetype)}getNormalSources(e){return this.sources.filter(t=>{let{filetypes:i,triggerOnly:n,enable:o}=t;return!(!o||n||i&&!i.includes(e)||this.disabledByLanguageId(t,e))})}checkTrigger(e,t,i){let{triggerCharacters:n,triggerPatterns:o}=e;return!n&&!o?!1:!!(i&&n&&n.includes(i)||o&&o.findIndex(s=>s.test(t))!==-1)}shouldTrigger(e,t){return this.getTriggerSources(e,t).length>0}getTriggerSources(e,t){let i=e.length?e[e.length-1]:"";return i?this.sources.filter(n=>{let{filetypes:o,enable:s}=n;return!s||o&&!o.includes(t)||this.disabledByLanguageId(n,t)?!1:this.checkTrigger(n,e,i)}):[]}addSource(e){let{name:t}=e;return this.names.includes(t)&&C.showMessage(`Source "${t}" recreated`,"warning"),this.sourceMap.set(t,e),f9.Disposable.create(()=>{this.sourceMap.delete(t)})}removeSource(e){let t=typeof e=="string"?e:e.name;e==this.sourceMap.get(t)&&this.sourceMap.delete(t)}async refresh(e){for(let t of this.sources)(!e||t.name==e)&&typeof t.refresh=="function"&&await Promise.resolve(t.refresh())}toggleSource(e){if(!e)return;let t=this.getSource(e);!t||typeof t.toggle=="function"&&t.toggle()}sourceStats(){let e=[],t=this.sources;for(let i of t)e.push({name:i.name,priority:i.priority,triggerCharacters:i.triggerCharacters||[],shortcut:i.shortcut||"",filetypes:i.filetypes||[],filepath:i.filepath||"",type:i.sourceType==Yr.Native?"native":i.sourceType==Yr.Remote?"remote":"service",disabled:!i.enable});return e}onDocumentEnter(e){let{sources:t}=this;for(let i of t)!i.enable||typeof i.onEnter=="function"&&i.onEnter(e)}createSource(e){if(!e.name||!e.doComplete){console.error("name and doComplete required for createSource");return}let t=new Tn(Object.assign({sourceType:Yr.Service},e));return this.addSource(t)}disabledByLanguageId(e,t){let i=b.env.disabledSources,n=i?i[t]:[];return Array.isArray(n)&&n.includes(e.name)}dispose(){z(this.disposables)}},Ze=new p9;var _a=S(W());function h9(r=0,e){for(let t=r;t=65&&r<=90}function d9(r,e){if(r==0)return!0;let t=e[r];if(!Gp(t))return!1;let i=e[r-1];return!!(!Gp(i)||m9(t)&&!m9(i))}function g9(r,e){if(e.length==0||r.length=r.length)return 0;let n=[],o=t[0],s=r.length,a=t.length==1;if(!Gp(o)){for(let c=e;ci||{}})}get isCompleting(){return this.completing.size>0}get isCanceled(){return this._canceled}get isEmpty(){return this.results.length==0}get startcol(){return this.option.col||0}get input(){return this.option.input}get isIncomplete(){return this.results.findIndex(e=>e.isIncomplete)!==-1}async completeSource(e){let{col:t}=this.option,i=Object.assign({},this.option),n=this.config.timeout;n=Math.max(Math.min(n,15e3),500);try{if(typeof e.shouldComplete=="function"&&!await Promise.resolve(e.shouldComplete(i)))return null;let o=Date.now(),s=this.tokenSources.get(e.name);s&&s.cancel();let a=new _a.CancellationTokenSource;this.tokenSources.set(e.name,a),await new Promise((l,u)=>{let{name:c}=e,f=setTimeout(()=>{this.nvim.command(`echohl WarningMsg| echom 'source ${e.name} timeout after ${n}ms'|echohl None`,!0),a.cancel()},n),p=!1,d=!1,h=!1,m=setTimeout(()=>{d||(h=!0,l(void 0))},sbe),y=()=>{d||(d=!0,v.dispose(),clearTimeout(m),clearTimeout(f),this.tokenSources.delete(c))},v=a.token.onCancellationRequested(()=>{v.dispose(),this.completing.delete(c),p=!0,y(),Uv.debug(`Source "${c}" cancelled`),l(void 0)});this.completing.add(c),Promise.resolve(e.doComplete(i,a.token)).then(x=>{if(this.completing.delete(c),p)return;y();let w=Date.now()-o;if(Uv.debug(`Source "${c}" takes ${w}ms`),x&&x.items&&x.items.length){if(x.priority=e.priority,x.source=c,h&&x.startcol&&x.startcol!=t)this.results=[x];else{let{results:E}=this,P=E.findIndex(k=>k.source==c);P!=-1?E.splice(P,1,x):E.push(x)}h&&this._onDidComplete.fire(),l(void 0)}else l(void 0)},x=>{this.completing.delete(c),y(),u(x)})})}catch(o){this.nvim.command(`echoerr 'Complete ${e.name} error: ${o.message.replace(/'/g,"''")}'`,!0),Uv.error("Complete error:",e.name,o)}}async completeInComplete(e){let{results:t,document:i}=this;t.filter(f=>!f.isIncomplete).forEach(f=>{f.items.forEach(p=>delete p.user_data)});let s=t.filter(f=>f.isIncomplete).map(f=>f.source),{input:a,colnr:l,linenr:u}=this.option;Object.assign(this.option,{input:e,line:i.getline(u-1),colnr:l+(e.length-a.length),triggerCharacter:null,triggerForInComplete:!0});let c=this.sources.filter(f=>s.includes(f.name));return await Promise.all(c.map(f=>this.completeSource(f))),this.filterResults(e,Math.floor(Date.now()/1e3))}filterResults(e,t=0){let{results:i}=this;i.sort((h,m)=>h.source=="tabnine"?1:m.source=="tabnine"?-1:m.priority-h.priority);let n=Date.now(),{bufnr:o}=this.option,{snippetIndicator:s,removeDuplicateItems:a,fixInsertedWord:l,asciiCharactersOnly:u}=this.config,c=!l||t==0?"":this.getFollowPart();if(i.length==0)return[];let f=[],p=no(e),d=new Set;for(let h=0,m=i.length;h{let y=h.sortText,v=m.sortText,x=h.filterText,w=m.filterText;if(h.score!=m.score)return m.score-h.score;if(h.priority!=m.priority)return m.priority-h.priority;if(y&&v&&y!=v)return y{let{priority:s,source:a}=o,l=s<90,u=n.get(a)||0;return i&&l&&u==i||t&&!l&&u==t?!1:(n.set(a,u+1),!0)})}hasMatch(e){let{results:t}=this;if(!t)return!1;let i=no(e);for(let n=0,o=t.length;nku(i,l.filterText||l.word))!==-1)return!0;return!1}async doComplete(){let e=this.option,{line:t,colnr:i,linenr:n,col:o}=this.option;if(this.config.localityBonus){let l=n-1;this.localBonus=this.document.getLocalifyBonus(_a.Position.create(l,e.col-1),_a.Position.create(l,i))}else this.localBonus=new Map;await Promise.all(this.sources.map(l=>this.completeSource(l)));let{results:s}=this;if(s.length==0)return[];let a=s.find(l=>l.startcol!=null&&l.startcol!=o);if(a){let{startcol:l}=a;e.col=l,e.input=Rt(t,l,i-1),this.results=[a]}return Uv.info(`Results from: ${this.results.map(l=>l.source).join(",")}`),this.filterResults(e.input,Math.floor(Date.now()/1e3))}resolveCompletionItem(e){let{results:t}=this;if(!t)return null;try{if(e.user_data){let{source:i}=JSON.parse(e.user_data);return t.find(o=>o.source==i).items.find(o=>o.user_data==e.user_data)}for(let i of t){let n=i.items.find(o=>o.abbr==e.abbr&&o.info==e.info);if(n)return n}return null}catch(i){return null}}getFollowPart(){let{colnr:e,line:t}=this.option,i=Mf(t,e-1);return i==t.length?"":t.slice(i-t.length).match(/^\S?[\w-]*/)[0]}dispose(){if(!this._canceled){this._onDidComplete.dispose(),this._canceled=!0;for(let e of this.tokenSources.values())e.cancel();this.tokenSources.clear(),this.sources=[],this.results=[]}}},v9=MC;var jHe=j()("floating"),NC=class{constructor(e,t){this.nvim=e;this.isVim=t;this.winid=0;this.bufnr=0}async show(e,t,i,n){let{nvim:o}=this;e=e.filter(c=>c.content.trim().length>0);let{lines:s,codes:a,highlights:l}=Om(e);if(s.length==0){this.close();return}let u=await o.call("coc#float#create_pum_float",[this.winid,this.bufnr,s,{codes:a,highlights:l,maxWidth:i.maxPreviewWidth,pumbounding:t}]);if(this.isVim&&o.command("redraw",!0),!(!u||u.length==0)&&(this.winid=u[0],this.bufnr=u[1],n.isCancellationRequested)){this.close();return}}close(){let{winid:e,nvim:t}=this;this.winid=0,!!e&&(t.call("coc#float#close",[e],!0),this.isVim&&t.command("redraw",!0))}},y9=NC;function qC(r,e){let t,i,n,o=0;function s(){t=arguments;let l=Date.now()-o;return n||(o!=0&&l>=e?a():n=setTimeout(a,e-l)),i}function a(){n=0,o=Date.now(),i=r.apply(null,t),t=null}return s.clear=()=>{n&&clearTimeout(n)},s}var us=j()("completion"),abe=["abbr","menu","info","kind","icase","dup","empty","user_data"],b9=class{constructor(){this.activated=!1;this.disposables=[];this.complete=null;this.recentScores={};this.changedTick=0;this.insertCharTs=0;this.insertLeaveTs=0}init(){this.config=this.getCompleteConfig(),this.floating=new y9(b.nvim,b.env.isVim),A.on(["InsertCharPre","MenuPopupChanged","TextChangedI","CursorMovedI","InsertLeave"],()=>{this.triggerTimer&&(clearTimeout(this.triggerTimer),this.triggerTimer=null)},this,this.disposables),A.on("InsertCharPre",this.onInsertCharPre,this,this.disposables),A.on("InsertLeave",this.onInsertLeave,this,this.disposables),A.on("InsertEnter",this.onInsertEnter,this,this.disposables),A.on("TextChangedP",this.onTextChangedP,this,this.disposables),A.on("TextChangedI",this.onTextChangedI,this,this.disposables);let e=qC(this.onPumChange.bind(this),b.isVim?200:100);A.on("CompleteDone",async t=>{this.currItem=null,this.cancelResolve(),this.floating.close(),await this.onCompleteDone(t)},this,this.disposables),A.on("MenuPopupChanged",t=>{if(!this.activated||this.isCommandLine)return;let{completed_item:i}=t,n=i.hasOwnProperty("word")?i:null;Ne(n,this.currItem)||(this.cancelResolve(),this.currItem=n,e(t))},this,this.disposables),b.onDidChangeConfiguration(t=>{t.affectsConfiguration("suggest")&&(this.config=this.getCompleteConfig())},null,this.disposables)}get nvim(){return b.nvim}get option(){return this.complete?this.complete.option:null}get isCommandLine(){var e;return(e=this.document)==null?void 0:e.uri.endsWith("%5BCommand%20Line%5D")}addRecent(e,t){!e||(this.recentScores[`${t}|${e}`]=Date.now())}get isActivated(){return this.activated}get document(){return this.option?b.getDocument(this.option.bufnr):null}getCompleteConfig(){let e=b.getConfiguration("suggest");function t(a,l){return e.get(a,l)}let i=t("keepCompleteopt",!1),n=t("autoTrigger","always");if(i&&n!="none"){let{completeOpt:a}=b;!a.includes("noinsert")&&!a.includes("noselect")&&(n="none")}let o=b.floatSupported&&t("floatEnable",!0),s=b.env.pumevent&&t("acceptSuggestionOnCommitCharacter",!1);return{autoTrigger:n,floatEnable:o,keepCompleteopt:i,defaultSortMethod:t("defaultSortMethod","length"),removeDuplicateItems:t("removeDuplicateItems",!1),disableMenuShortcut:t("disableMenuShortcut",!1),acceptSuggestionOnCommitCharacter:s,disableKind:t("disableKind",!1),disableMenu:t("disableMenu",!1),previewIsKeyword:t("previewIsKeyword","@,48-57,_192-255"),enablePreview:t("enablePreview",!1),enablePreselect:t("enablePreselect",!1),maxPreviewWidth:t("maxPreviewWidth",80),triggerCompletionWait:t("triggerCompletionWait",100),labelMaxLength:t("labelMaxLength",200),triggerAfterInsertEnter:t("triggerAfterInsertEnter",!1),noselect:t("noselect",!0),numberSelect:t("numberSelect",!1),maxItemCount:t("maxCompleteItemCount",50),timeout:t("timeout",500),minTriggerInputLength:t("minTriggerInputLength",1),snippetIndicator:t("snippetIndicator","~"),fixInsertedWord:t("fixInsertedWord",!0),localityBonus:t("localityBonus",!0),highPrioritySourceLimit:t("highPrioritySourceLimit",null),lowPrioritySourceLimit:t("lowPrioritySourceLimit",null),asciiCharactersOnly:t("asciiCharactersOnly",!1)}}async startCompletion(e){this.pretext=Rt(e.line,0,e.colnr-1);try{await this._doComplete(e)}catch(t){this.stop(!1),us.error("Complete error:",t.stack)}}async resumeCompletion(e=!1){let{document:t,complete:i}=this;if(!t||i.isCanceled||!i.results||i.results.length==0)return;let n=this.getResumeInput();if(n==this.input&&!e)return;if(!n||n.endsWith(" ")||!n.startsWith(i.input)){this.stop();return}this.input=n;let o=[];if(i.isIncomplete){await t.patchChange();let{changedtick:s}=t;if(o=await i.completeInComplete(n),i.isCanceled||t.changedtick!=s)return}else o=i.filterResults(n);if(!i.isCompleting&&o.length===0){this.stop();return}await this.showCompletion(i.option.col,o)}hasSelected(){return b.env.pumevent?this.currItem!=null:!this.config.noselect}async showCompletion(e,t){let{nvim:i,document:n,option:o}=this,{numberSelect:s,disableKind:a,labelMaxLength:l,disableMenuShortcut:u,disableMenu:c}=this.config,f=this.config.enablePreselect?t.findIndex(h=>h.preselect):-1;s&&o.input.length&&!/^\d/.test(o.input)&&(t=t.map((h,m)=>{let y=m+1;return m<9?Object.assign({},h,{abbr:h.abbr?`${y} ${h.abbr}`:`${y} ${h.word}`}):h}),i.call("coc#_map",[],!0)),this.changedTick=n.changedtick;let p=abe.slice();a&&(p=p.filter(h=>h!="kind")),c&&(p=p.filter(h=>h!="menu"));let d=t.map(h=>{let m={word:h.word,equal:1};for(let y of p)h.hasOwnProperty(y)&&(u&&y=="menu"?m[y]=h[y].replace(/\[.+\]$/,""):y=="abbr"&&h[y].length>l?m[y]=h[y].slice(0,l):m[y]=h[y]);return m});i.call("coc#_do_complete",[e,d,f],!0)}async _doComplete(e){let{source:t}=e,{nvim:i,config:n}=this,o=b.getDocument(e.bufnr);if(!o||!o.attached)return;e.filetype=o.filetype,this.input=e.input;let s=[];if(t==null)s=Ze.getCompleteSources(e);else{let u=Ze.getSource(t);u&&s.push(u)}if(!s.length||(await o.patchChange(),o.changedtick!=e.changedtick))return;let a=new v9(e,o,this.recentScores,n,s,i);this.start(a);let l=await this.complete.doComplete();if(!a.isCanceled){if(l.length==0&&!a.isCompleting){this.stop();return}a.onDidComplete(async()=>{if(this.currItem!=null)return;let u=this.getResumeInput();if(a.isCanceled||u==null)return;let{input:c}=this.option;if(u==c){let f=a.filterResults(u,Math.floor(Date.now()/1e3));await this.showCompletion(e.col,f)}else await this.resumeCompletion()}),l.length&&(this.getResumeInput()==e.input?await this.showCompletion(e.col,l):await this.resumeCompletion(!0))}}async onTextChangedP(e,t){let{option:i,document:n}=this,o=this.pretext=t.pre;if(!i||i.bufnr!=e||t.changedtick==this.changedTick)return;let s=this.latestInsert!=null;if(this.lastInsert=null,t.pre.match(/^\s*/)[0]!==i.line.match(/^\s*/)[0]){us.warn("Complete stopped by indent change."),this.stop();return}!s||!o||(Ze.shouldTrigger(o,n.filetype)?await this.triggerCompletion(n,o):await this.resumeCompletion())}async onTextChangedI(e,t){let{nvim:i,latestInsertChar:n,option:o}=this,s=this.pretext==t.pre,a=this.pretext=t.pre;this.lastInsert=null;let l=b.getDocument(e);if(!!l){if(!this.activated){if(!n)return;if(Ze.getTriggerSources(a,l.filetype).length){await this.triggerCompletion(l,this.pretext);return}this.triggerTimer=setTimeout(async()=>{await this.triggerCompletion(l,a)},this.config.triggerCompletionWait);return}if(!(!o||e!=o.bufnr)){if(o.linenr!=t.lnum||o.col>=t.col-1){this.stop();return}if(s&&!n){this.stop(!1);return}if(a&&this.currItem&&this.config.acceptSuggestionOnCommitCharacter&&n){let u=this.getCompleteItem(this.currItem),c=a[a.length-1];if(Ze.shouldCommit(u,c)){let{linenr:f,col:p,line:d,colnr:h}=this.option;this.stop();let{word:m}=u,y=`${d.slice(0,p)}${m}${n}${d.slice(h-1)}`;await i.call("coc#util#setline",[f,y]);let v=p+m.length+2;await i.call("cursor",[f,v]),await l.patchChange();return}}Ze.shouldTrigger(a,l.filetype)?await this.triggerCompletion(l,a):await this.resumeCompletion()}}}async triggerCompletion(e,t){if(!e||!e.attached){us.warn("Document not attached, suggest disabled.");return}if(!this.shouldTrigger(e,t))return;if(e.getVar("suggest_disable")){us.warn("Suggest disabled by b:coc_suggest_disable");return}await e.patchChange();let[n,o]=await this.nvim.eval('[get(b:,"coc_suggest_disable",0),coc#util#get_complete_option()]');if(n==1){us.warn("Suggest disabled by b:coc_suggest_disable");return}if(o.blacklist&&o.blacklist.includes(o.input)){us.warn("Suggest disabled by b:coc_suggest_blacklist",o.blacklist);return}t.length&&(o.triggerCharacter=t.slice(-1)),us.debug("trigger completion with",o),await this.startCompletion(o)}async onCompleteDone(e){let{document:t,isActivated:i}=this;if(!i||!t||!e.hasOwnProperty("word"))return;let n=Object.assign({},this.option),o=this.getCompleteItem(e);if(this.stop(!1),!o)return;let s=this.insertCharTs,a=this.insertLeaveTs;try{if(await Ze.doCompleteResolve(o,new $C.CancellationTokenSource().token),this.addRecent(o.word,t.bufnr),await He(50),this.insertCharTs!=s||this.insertLeaveTs!=a)return;let[l,u,c]=await this.nvim.eval("[pumvisible(),line('.'),strpart(getline('.'), 0, col('.') - 1)]");if(l||u!=n.linenr||this.activated||!c.endsWith(o.word))return;await t.patchChange(),await Ze.doCompleteDone(o,n)}catch(l){us.error("error on complete done",l.stack)}}async onInsertLeave(){this.insertLeaveTs=Date.now(),this.stop(!1)}async onInsertEnter(e){if(!this.config.triggerAfterInsertEnter||this.config.autoTrigger!=="always")return;let t=b.getDocument(e);if(!t)return;let i=await this.nvim.eval("strpart(getline('.'), 0, col('.') - 1)");!i||await this.triggerCompletion(t,i)}async onInsertCharPre(e){this.lastInsert={character:e,timestamp:Date.now()},this.insertCharTs=this.lastInsert.timestamp}get latestInsert(){let{lastInsert:e}=this;return!e||Date.now()-e.timestamp>500?null:e}get latestInsertChar(){let{latestInsert:e}=this;return e?e.character:""}shouldTrigger(e,t){let i=this.config.autoTrigger;if(i=="none")return!1;if(Ze.shouldTrigger(t,e.filetype))return!0;if(i!=="always"||this.isActivated)return!1;let n=t.slice(-1);if(n&&(e.isWord(t.slice(-1))||n.codePointAt(0)>255)){let o=this.config.minTriggerInputLength;return o==1?!0:this.getInput(e,t).length>=o}return!1}async onPumChange(e){if(!this.activated)return;let{completed_item:t,col:i,row:n,height:o,width:s,scrollbar:a}=e,l={col:i,row:n,height:o,width:s,scrollbar:a},u=this.getCompleteItem(t);if(!u){this.floating.close();return}let c=this.resolveTokenSource=new $C.CancellationTokenSource,{token:f}=c;if(await Ze.doCompleteResolve(u,f),this.resolveTokenSource=null,f.isCancellationRequested)return;let p=u.documentation;if(!p&&u.info){let{info:d}=u;p=[{filetype:/^[\w-\s.,\t]+$/.test(d)?"txt":this.document.filetype,content:d}]}!this.isActivated||(!p||p.length==0?this.floating.close():(this.config.floatEnable&&await this.floating.show(p,l,{maxPreviewWidth:this.config.maxPreviewWidth},f),this.isActivated||this.floating.close()))}start(e){let{activated:t}=this;this.activated=!0,t&&this.complete.dispose(),this.complete=e,this.config.keepCompleteopt||this.nvim.command(`noa set completeopt=${this.completeOpt}`,!0)}cancelResolve(){this.resolveTokenSource&&(this.resolveTokenSource.cancel(),this.resolveTokenSource=null)}stop(e=!0){let{nvim:t}=this;!this.activated||(this.cancelResolve(),this.currItem=null,this.activated=!1,this.complete&&(this.complete.dispose(),this.complete=null),t.pauseNotification(),e&&t.call("coc#_hide",[],!0),this.floating.close(),this.config.numberSelect&&t.call("coc#_unmap",[],!0),this.config.keepCompleteopt||this.nvim.command(`noa set completeopt=${b.completeOpt}`,!0),t.command("let g:coc#_context['candidates'] = []",!0),t.call("coc#_cancel",[],!0),t.resumeNotification(!1,!0))}getInput(e,t){let i="";for(let n=t.length-1;n>=0;n--){let o=n==0?null:t[n-1];if(!o||!e.isWord(o)){i=t.slice(n,t.length);break}}return i}getResumeInput(){let{option:e,pretext:t}=this;if(!e)return null;let i=Buffer.from(t,"utf8");if(i.lengthMe(s.range.start,t.start)==0)!==-1)return!1;let n=gD(this.range.start,e);return n.line==0&&n.character==0||this.adjustPosition(n.character,n.line),!0}get isPlainText(){return this._placeholders.length>1?!1:this._placeholders.every(e=>e.value=="")}get finalCount(){return this._placeholders.filter(e=>e.isFinalTabstop).length}toString(){return this.tmSnippet.toString()}get range(){let{position:e}=this,t=this.tmSnippet.toString(),n=kt.create("untitled:/1","snippet",0,t).positionAt(t.length),o=n.line==0?e.character+n.character:n.character;return oo.Range.create(e,oo.Position.create(e.line+n.line,o))}get firstPlaceholder(){let e=0;for(let t of this._placeholders)t.index!=0&&(e==0||t.indexe)&&(e=t.index);return this.getPlaceholder(e)}getPlaceholderById(e){return this._placeholders.find(t=>t.id==e)}getPlaceholder(e){let t=this._placeholders.filter(n=>n.index==e),i=t.filter(n=>!n.transform);return i.length?i[0]:t[0]}getPrevPlaceholder(e){if(e==0)return this.lastPlaceholder;let t=this.getPlaceholder(e-1);return t||this.getPrevPlaceholder(e-1)}getNextPlaceholder(e){let t=this._placeholders.map(o=>o.index),i=Math.max.apply(null,t);if(e>=i)return this.finalPlaceholder;let n=this.getPlaceholder(e+1);return n||this.getNextPlaceholder(e+1)}get finalPlaceholder(){return this._placeholders.find(e=>e.isFinalTabstop)}getPlaceholderByRange(e){return this._placeholders.find(t=>Ji(e,t.range))}insertSnippet(e,t,i){let{start:n}=e.range,o=oo.Position.create(i.start.line-n.line,i.start.line==n.line?i.start.character-n.character:i.start.character),s=oo.Position.create(i.end.line-n.line,i.end.line==n.line?i.end.character-n.character:i.end.character),a=oo.Range.create(o,s),l=this.tmSnippet.insertSnippet(t,e.id,a);return this.update(),l}updatePlaceholder(e,t){let{start:i,end:n}=t.range,{range:o}=this,{value:s,id:a,index:l}=e,u=jB(e.range,s,t),c=0;if(!u.includes(` +`)){for(let d of this._placeholders)if(d.index==l&&d.id{let p=e.offset(c),d=n.positionAt(p),h={line:t+d.line,character:d.line==0?i+d.character:d.character},m;if(c instanceof yn){let w=c.name;l.has(w)?m=l.get(w):(l.set(w,u),m=u,u=u+1)}else m=c.index;let y=c.toString(),v=y.split(/\r?\n/),x={range:oo.Range.create(h,{line:h.line+v.length-1,character:v.length==1?h.character+y.length:v[v.length-1].length}),transform:c.transform!=null,line:h.line,id:f,index:m,value:y,isVariable:c instanceof yn,isFinalTabstop:c.index===0};if(Object.defineProperty(x,"snippet",{enumerable:!1}),c instanceof ei&&c.choice){let{options:w}=c.choice;w&&w.length&&(x.choice=w.map(E=>E.value))}return x})}};var Qp=S(require("path"));var uze=j()("snippets-variable"),ed=class{constructor(){this._variableToValue={};let e=new Date;Object.assign(this._variableToValue,{CURRENT_YEAR:e.getFullYear().toString(),CURRENT_YEAR_SHORT:e.getFullYear().toString().slice(-2),CURRENT_MONTH:(e.getMonth()+1).toString(),CURRENT_DATE:e.getDate().toString(),CURRENT_HOUR:e.getHours().toString(),CURRENT_MINUTE:e.getMinutes().toString(),CURRENT_SECOND:e.getSeconds().toString(),CURRENT_DAY_NAME:e.toLocaleString("en-US",{weekday:"long"}),CURRENT_DAY_NAME_SHORT:e.toLocaleString("en-US",{weekday:"short"}),CURRENT_MONTH_NAME:e.toLocaleString("en-US",{month:"long"}),CURRENT_MONTH_NAME_SHORT:e.toLocaleString("en-US",{month:"short"}),TM_FILENAME:null,TM_FILENAME_BASE:null,TM_DIRECTORY:null,TM_FILEPATH:null,YANK:null,TM_LINE_INDEX:null,TM_LINE_NUMBER:null,TM_CURRENT_LINE:null,TM_CURRENT_WORD:null,TM_SELECTED_TEXT:null,CLIPBOARD:null})}async resovleValue(e){let{nvim:t}=C;if(["TM_FILENAME","TM_FILENAME_BASE","TM_DIRECTORY","TM_FILEPATH"].includes(e)){let i=await t.eval('expand("%:p")');if(e=="TM_FILENAME")return Qp.default.basename(i);if(e=="TM_FILENAME_BASE")return Qp.default.basename(i,Qp.default.extname(i));if(e=="TM_DIRECTORY")return Qp.default.dirname(i);if(e=="TM_FILEPATH")return i}if(e=="YANK")return await t.call("getreg",['""']);if(e=="TM_LINE_INDEX")return(await t.call("line",["."])-1).toString();if(e=="TM_LINE_NUMBER")return(await t.call("line",["."])).toString();if(e=="TM_CURRENT_LINE")return await t.call("getline",["."]);if(e=="TM_CURRENT_WORD")return await t.eval("expand('')");if(e=="TM_SELECTED_TEXT")return await t.eval("get(g:,'coc_selected_text', '')");if(e=="CLIPBOARD")return await t.eval("@*")}async resolve(e){let t=e.name,i=this._variableToValue[t];if(i!=null)return i.toString();let n=await this.resovleValue(t);return n||(e.children&&e.children.length?e.toString():this._variableToValue.hasOwnProperty(t)?"":t)}};var Mu=j()("snippets-session"),jC=class{constructor(e,t){this.nvim=e;this.bufnr=t;this._isActive=!1;this._currId=0;this.applying=!1;this.preferComplete=!1;this._snippet=null;this._onCancelEvent=new Lu.Emitter;this.onCancel=this._onCancelEvent.event;let i=b.getConfiguration("coc.preferences"),n=b.getConfiguration("suggest");this.preferComplete=i.get("preferCompleteThanJumpPlaceholder",n.get("preferCompleteThanJumpPlaceholder",!1))}async start(e,t=!0,i){let{document:n}=this;if(!n||!n.attached)return!1;if(A.fire("InsertSnippet",[]).logError(),!i){let d=await C.getCursorPosition();i=Lu.Range.create(d,d)}let o=i.start,s=await b.getFormatOptions(this.document.uri);await n.patchChange(!0);let a=n.getline(o.line),l=a.match(/^\s*/)[0],u=lbe(e,l,s),c=new ed,f=new BC(u,o,c);await f.init();let p=Lu.TextEdit.replace(i,f.toString());if(e.endsWith(` +`)&&a.slice(o.character).length&&(p.newText=p.newText+l,u=u+l),this.applying=!0,await n.applyEdits([p]),this.applying=!1,this._isActive){let d=this.findPlaceholder(i);if(d&&!d.isFinalTabstop){let h=this.snippet.insertSnippet(d,u,i),m=this.snippet.getPlaceholder(h);return this._currId=m.id,t&&await this.selectPlaceholder(m),!0}}if(f.isPlainText){this.deactivate();let d=f.finalPlaceholder;return await C.moveTo(d.range.start),!1}return this._snippet=f,this._currId=f.firstPlaceholder.id,t&&await this.selectPlaceholder(f.firstPlaceholder),this.activate(),!0}activate(){this._isActive||(this._isActive=!0,this.nvim.call("coc#snippet#enable",[],!0))}deactivate(){this._isActive&&(this._isActive=!1,this._snippet=null,this.nvim.call("coc#snippet#disable",[],!0),Mu.debug("[SnippetManager::cancel]")),this._onCancelEvent.fire(void 0),this._onCancelEvent.dispose()}get isActive(){return this._isActive}async nextPlaceholder(){if(!this.isActive)return;await this.document.patchChange();let e=this.placeholder,t=this.snippet.getNextPlaceholder(e.index);await this.selectPlaceholder(t)}async previousPlaceholder(){if(!this.isActive)return;await this.document.patchChange();let e=this.placeholder,t=this.snippet.getPrevPlaceholder(e.index);await this.selectPlaceholder(t)}async synchronizeUpdatedPlaceholders(e){if(!this.isActive||!this.document||this.applying)return;let t={range:e.range,newText:e.text},{snippet:i}=this;if(i.adjustTextEdit(t))return;if(Me(t.range.start,i.range.end)>0){if(!t.newText)return;Mu.info("Content change after snippet, cancelling snippet session"),this.deactivate();return}let o=this.findPlaceholder(t.range);if(!o){Mu.info("Change outside placeholder, cancelling snippet session"),this.deactivate();return}if(o.isFinalTabstop&&i.finalCount<=1){Mu.info("Change final placeholder, cancelling snippet session"),this.deactivate();return}this._currId=o.id;let{edits:s,delta:a}=i.updatePlaceholder(o,t);!s.length||(this.applying=!0,await this.document.applyEdits(s),this.applying=!1,a&&await this.nvim.call("coc#util#move_cursor",a))}async selectCurrentPlaceholder(e=!0){let t=this.snippet.getPlaceholderById(this._currId);t&&await this.selectPlaceholder(t,e)}async selectPlaceholder(e,t=!0){let{nvim:i,document:n}=this;if(!n||!e)return;let{start:o,end:s}=e.range,a=s.character-o.character,l=ue(n.getline(o.line).slice(0,o.character))+1;this._currId=e.id,e.choice?(await i.call("coc#snippet#show_choices",[o.line+1,l,a,e.choice]),t&&i.call("coc#util#do_autocmd",["CocJumpPlaceholder"],!0)):await this.select(e,t)}async select(e,t=!0){let{range:i,value:n,isFinalTabstop:o}=e,{document:s,nvim:a}=this,{start:l,end:u}=i,{textDocument:c}=s,f=c.offsetAt(u)-c.offsetAt(l),p=s.getline(l.line),d=p?ue(p.slice(0,l.character)):0,h=s.getline(u.line),m=h?ue(h.slice(0,u.character)):0;a.setVar("coc_last_placeholder",{current_text:n,start:{line:l.line,col:d},end:{line:u.line,col:m}},!0);let[y,v,x,w]=await a.eval("[&virtualedit, &selection, pumvisible(), mode()]"),E="";if(x&&this.preferComplete){let P=cs.hasSelected()?"":"\\";await a.eval(`feedkeys("${P}\\", 'in')`);return}w!="n"&&(E+="\\"),f==0?d==0||!w.startsWith("i")&&d`),w=="i"&&E=="\\a"&&(E=""),a.pauseNotification(),a.setOption("virtualedit","onemore",!0),a.call("cursor",[l.line+1,d+(E=="a"?0:1)],!0),E&&a.call("eval",[`feedkeys("${E}", 'in')`],!0),w=="i"&&a.call("coc#_cancel",[],!0),a.setOption("virtualedit",y,!0),o&&(this.snippet.finalCount==1?(Mu.info("Jump to final placeholder, cancelling snippet session"),this.deactivate()):a.call("coc#snippet#disable",[],!0)),b.env.isVim&&a.command("redraw",!0),await a.resumeNotification(),t&&a.call("coc#util#do_autocmd",["CocJumpPlaceholder"],!0)}async getVirtualCol(e,t){let{nvim:i}=this;return await i.eval(`virtcol([${e}, ${t}])`)}async checkPosition(){if(!this.isActive)return;let e=await C.getCursorPosition();this.snippet&&Wt(e,this.snippet.range)!=0&&(Mu.info("Cursor insert out of range, cancelling snippet session"),this.deactivate())}findPlaceholder(e){if(!this.snippet)return null;let{placeholder:t}=this;return t&&Ji(e,t.range)?t:this.snippet.getPlaceholderByRange(e)||null}get placeholder(){return this.snippet?this.snippet.getPlaceholderById(this._currId):null}get snippet(){return this._snippet}get document(){return b.getDocument(this.bufnr)}};function lbe(r,e,t){let i=r.split(/\r?\n/),n=t.insertSpaces?" ".repeat(t.tabSize):" ",o=t.tabSize||2;return i=i.map((s,a)=>{let l=s.match(/^\s*/)[0],u=l,c=l.startsWith(" ");return c&&t.insertSpaces?u=n.repeat(l.length):!c&&!t.insertSpaces&&(u=n.repeat(l.length/o)),(a==0||s.length==0?"":e)+u+s.slice(l.length)}),i.join(` +`)}var Rze=j()("snippets-manager"),w9=class{constructor(){this.sessionMap=new Map;this.disposables=[];b.onDidChangeTextDocument(async e=>{let t=this.getSession(e.bufnr);t&&await t.synchronizeUpdatedPlaceholders(e.contentChanges[0])},null,this.disposables),b.onDidCloseTextDocument(e=>{let t=b.getDocument(e.uri);if(!t)return;let i=this.getSession(t.bufnr);i&&i.deactivate()},null,this.disposables),A.on("BufEnter",async e=>{let t=this.getSession(e);!this.statusItem||(t&&t.isActive?this.statusItem.show():this.statusItem.hide())},null,this.disposables),A.on("InsertEnter",async()=>{let{session:e}=this;!e||await e.checkPosition()},null,this.disposables)}init(){let e=b.getConfiguration("coc.preferences");this.statusItem=C.createStatusBarItem(0),this.statusItem.text=e.get("snippetStatusText","SNIP")}async insertSnippet(e,t=!0,i){let{bufnr:n}=b,o=this.getSession(n);o||(o=new jC(b.nvim,n),this.sessionMap.set(n,o),o.onCancel(()=>{this.sessionMap.delete(n),b.bufnr==n&&this.statusItem.hide()}));let s=await o.start(e,t,i);return s&&this.statusItem.show(),s}async selectCurrentPlaceholder(e=!0){let{session:t}=this;if(t)return await t.selectCurrentPlaceholder(e)}async nextPlaceholder(){let{session:e}=this;if(e)return await e.nextPlaceholder();b.nvim.call("coc#snippet#disable",[],!0),this.statusItem.hide()}async previousPlaceholder(){let{session:e}=this;if(e)return await e.previousPlaceholder();b.nvim.call("coc#snippet#disable",[],!0),this.statusItem.hide()}cancel(){let e=this.getSession(b.bufnr);if(e)return e.deactivate();b.nvim.call("coc#snippet#disable",[],!0),this.statusItem&&this.statusItem.hide()}get session(){let e=this.getSession(b.bufnr);return e&&e.isActive?e:null}isActived(e){let t=this.getSession(e);return t&&t.isActive}jumpable(){let{session:e}=this;if(!e)return!1;let t=e.placeholder;return!!(t&&!t.isFinalTabstop)}getSession(e){return this.sessionMap.get(e)}async resolveSnippet(e){let i=new Ho().parse(e,!0),n=new ed;return await i.resolveVariables(n),i}dispose(){this.cancel();for(let e of this.disposables)e.dispose()}},Ft=new w9;var Wze=j()("commands"),x9=class{constructor(e,t,i,n=!1){this.id=e;this.impl=t;this.thisArg=i;this.internal=n}execute(...e){let{impl:t,thisArg:i}=this;return t.apply(i,e||[])}dispose(){this.thisArg=null,this.impl=null}},D9=class{constructor(){this.commands=new Map;this.titles=new Map;this.onCommandList=[]}init(e,t){this.mru=b.createMru("commands"),this.register({id:"vscode.open",execute:async i=>{e.call("coc#util#open_url",i.toString(),!0)}},!0),this.register({id:"workbench.action.reloadWindow",execute:async()=>{await e.command("edit")}},!0),this.register({id:"editor.action.insertSnippet",execute:async i=>(e.call("coc#_cancel",[],!0),await Ft.insertSnippet(i.newText,!0,i.range))},!0),this.register({id:"editor.action.doCodeAction",execute:async i=>{await t.cocAction("doCodeAction",i)}},!0),this.register({id:"editor.action.triggerSuggest",execute:async()=>{await He(60),e.call("coc#start",[],!0)}},!0),this.register({id:"editor.action.triggerParameterHints",execute:async()=>{await He(60),await t.cocAction("showSignatureHelp")}},!0),this.register({id:"editor.action.addRanges",execute:async i=>{await t.cocAction("addRanges",i)}},!0),this.register({id:"editor.action.restart",execute:async()=>{await He(30),e.command("CocRestart",!0)}},!0),this.register({id:"editor.action.showReferences",execute:async(i,n,o)=>{await b.showLocations(o)}},!0),this.register({id:"editor.action.rename",execute:async(i,n)=>{await b.jumpTo(i,n),await t.cocAction("rename")}},!0),this.register({id:"editor.action.format",execute:async()=>{await t.cocAction("format")}},!0),this.register({id:"workspace.diffDocument",execute:async()=>{let i=await b.document;!i||await e.call("coc#util#diff_content",[i.getLines()])}}),this.register({id:"workspace.clearWatchman",execute:async()=>{(await C.runTerminalCommand("watchman watch-del-all")).success&&C.showMessage("Cleared watchman watching directories.")}},!1,"run watch-del-all for watchman to free up memory."),this.register({id:"workspace.workspaceFolders",execute:async()=>{let n=b.workspaceFolders.map(o=>$.parse(o.uri).fsPath);await C.echoLines(n)}},!1,"show opened workspaceFolders."),this.register({id:"workspace.renameCurrentFile",execute:async()=>{await b.renameCurrent()}},!1,"change current filename to a new name and reload it."),this.register({id:"extensions.toggleAutoUpdate",execute:async()=>{let i=b.getConfiguration("coc.preferences");i.get("extensionUpdateCheck","daily")=="never"?(i.update("extensionUpdateCheck","daily",!0),C.showMessage("Extension auto update enabled.","more")):(i.update("extensionUpdateCheck","never",!0),C.showMessage("Extension auto update disabled.","more"))}},!1,"toggle auto update of extensions."),this.register({id:"workspace.diagnosticRelated",execute:()=>St.jumpRelated()},!1,"jump to related locations of current diagnostic."),this.register({id:"workspace.showOutput",execute:async i=>{if(i)C.showOutputChannel(i);else{let n=b.channelNames;if(n.length==0)return;if(n.length==1)C.showOutputChannel(n[0]);else{let o=await C.showQuickpick(n);if(o==-1)return;let s=n[o];C.showOutputChannel(s)}}}},!1,"open output buffer to show output from languageservers or extensions."),this.register({id:"document.echoFiletype",execute:async()=>{let i=await e.call("bufnr","%"),n=b.getDocument(i);!n||await C.echoLines([n.filetype])}},!1,"echo the mapped filetype of the current buffer"),this.register({id:"document.renameCurrentWord",execute:async()=>{let i=await e.call("bufnr","%"),n=b.getDocument(i);if(!n)return;let o=await t.cocAction("getWordEdit");if(!o){C.showMessage("Invalid position","warning");return}let s=[],{changes:a,documentChanges:l}=o;if(a){let u=a[n.uri];u&&(s=u.map(c=>c.range))}else if(l)for(let u of l)Wv.TextDocumentEdit.is(u)&&u.textDocument.uri==n.uri&&(s=u.edits.map(c=>c.range));s.length&&await t.cocAction("addRanges",s)}},!1,"rename word under cursor in current buffer by use multiple cursors."),this.register({id:"document.jumpToNextSymbol",execute:async()=>{let i=await b.document;if(!i)return;let n=await t.cocAction("symbolRanges");if(!n)return;let{textDocument:o}=i,s=await C.getOffset();n.sort((a,l)=>a.start.line!=l.start.line?a.start.line-l.start.line:a.start.character-l.start.character);for(let a=0;a<=n.length-1;a++)if(o.offsetAt(n[a].start)>s){await C.moveTo(n[a].start);return}await C.moveTo(n[0].start)}},!1,"Jump to next symbol highlight position."),this.register({id:"document.jumpToPrevSymbol",execute:async()=>{let i=await b.document;if(!i)return;let n=await t.cocAction("symbolRanges");if(!n)return;let{textDocument:o}=i,s=await C.getOffset();n.sort((a,l)=>a.start.line!=l.start.line?a.start.line-l.start.line:a.start.character-l.start.character);for(let a=n.length-1;a>=0;a--)if(o.offsetAt(n[a].end){this.commands.delete(e)})}executeCommand(e,...t){let i=this.commands.get(e);if(!i)throw new Error(`Command: ${e} not found`);return Promise.resolve(i.execute.apply(i,t))}async addRecent(e){await this.mru.add(e),await b.nvim.command('silent! call repeat#set("\\(coc-command-repeat)", -1)')}async repeatCommand(){let t=(await this.mru.load())[0];t&&(await this.executeCommand(t),await b.nvim.command('silent! call repeat#set("\\(coc-command-repeat)", -1)'))}},me=new D9;var $u=S(jn());var Nu=S(Bl()),qu=S(W());var td=S(jn());var Vze=j()("cursors-range"),UC=class{constructor(e,t,i,n,o){this.line=e;this.start=t;this.end=i;this.text=n;this.preCount=o;this.currStart=t,this.currEnd=i}add(e,t){let{text:i,preCount:n}=this,o=e==0?"":i.slice(0,e),s=i.slice(e);this.text=`${o}${t}${s}`,this.currStart=this.currStart+n*t.length,this.currEnd=this.currEnd+(n+1)*t.length}replace(e,t,i=""){let{text:n,preCount:o}=this,s=e==0?"":n.slice(0,e),a=n.slice(t);this.text=s+i+a;let l=t-e-i.length;this.currStart=this.currStart-o*l,this.currEnd=this.currEnd-(o+1)*l}get range(){return td.Range.create(this.line,this.start,this.line,this.end)}get currRange(){return td.Range.create(this.line,this.currStart,this.line,this.currEnd)}applyEdit(e){let{range:t,newText:i}=e,n=t.start.character,o=t.end.character;n==o?this.add(n-this.currStart,i):this.replace(n-this.currStart,o-this.currStart,i)}adjustFromEdit(e){let{range:t,newText:i}=e;if(Me(t.start,td.Position.create(this.line,this.currEnd))>0)return;let n=i.split(` +`),o=n.length-(t.end.line-t.start.line+1);if(this.line=this.line+o,t.end.line==this.line){let s=t.start.line==t.end.line?t.end.character-t.start.character:t.end.character;n.length>1&&t.start.line==t.end.line&&(s=s+t.start.character);let a=0;n.length>1?a=n[n.length-1].length:t.start.line==t.end.line?a=i.length:a=t.start.character+i.length;let l=a-s;for(let u of["start","end","currStart","currEnd"])this[u]+=l}}sync(){this.start=this.currStart,this.end=this.currEnd}get textEdit(){return{range:this.range,newText:this.text}}},WC=UC;var rd=S(W());function HC(r,e){let t=[];for(let i=e.start.line;i<=e.end.line;i++){let n=r.getline(i)||"",o=i==e.start.line?e.start.character:0,s=i==e.end.line?e.end.character:n.length;o!=s&&t.push(rd.Range.create(i,o,i,s))}return t}function S9(r,e){let{start:t,end:i}=e;t.line>i.line&&([t,i]=[i,t]);let n=t.character{this.cancel()},!0)),this.disposables.push(b.registerLocalKeymap("n",o,async()=>{if(!this.activated)return;let a=this.ranges.map(u=>u.currRange),l=await C.getCursorPosition();for(let u of a)if(Me(u.start,l)>0){await C.moveTo(u.start);return}a.length&&await C.moveTo(a[0].start)},!0)),this.disposables.push(b.registerLocalKeymap("n",s,async()=>{if(!this.activated)return;let a=this.ranges.map(u=>u.currRange);a.reverse();let l=await C.getCursorPosition();for(let u of a)if(Me(u.end,l)<0){await C.moveTo(u.start);return}a.length&&await C.moveTo(a[a.length-1].start)},!0)),this.doc.onDocumentChange(this.onChange,this,this.disposables)}async onChange(e){if(!this.activated||this.ranges.length==0||this.changing)return;let t=e.contentChanges[0],{text:i,range:n}=t,o=this.ranges.some(l=>ql(n,l.currRange)),s=this.ranges[0].currRange.start;if(i.endsWith(` +`)&&Me(s,n.end)==0&&(o=!1),!o){this.ranges.forEach(l=>{l.adjustFromEdit({range:n,newText:i})}),this.doHighlights(),this.textDocument=this.doc.textDocument;return}this.changed=!0;let a=this.getTextRange(n,i);a?await this.applySingleEdit(a,{range:n,newText:i}):(this.applyComposedEdit(e.original,{range:n,newText:i}),this.activated&&(this.ranges.forEach(l=>{l.sync()}),this.textDocument=this.doc.textDocument))}doHighlights(){let{nvim:e,buffer:t,ranges:i}=this;t.clearNamespace("cursors");let n=i.map(o=>o.currRange);t.highlightRanges("cursors","CocCursorRange",n),e.command("redraw",!0)}addRanges(e){let{nvim:t,doc:i}=this;if(this.changed)return C.showMessage("Can't add ranges after range change."),!1;this.ranges=this.ranges.filter(a=>{let{currRange:l}=a;return!e.some(u=>Mm(u,l))});let{textDocument:n}=i;for(let a of e){let{line:l}=a.start,u=new WC(l,a.start.character,a.end.character,n.getText(a),0);this.ranges.push(u)}this.ranges.sort((a,l)=>Me(a.range.start,l.range.start));let o=0,s=-1;for(let a of this.ranges){let{line:l}=a;l!=s&&(o=0),a.preCount=o,o=o+1,s=l}return t.pauseNotification(),this.doHighlights(),t.resumeNotification(!1,!0),!0}cancel(){if(!this.activated)return;let{nvim:e}=this;this.activated=!1;let{cancelKey:t,nextKey:i,previousKey:n}=this.config;e.pauseNotification(),this.buffer.clearNamespace("cursors"),this.buffer.setVar("coc_cursors_activated",0,!0),e.command("redraw",!0),e.resumeNotification(!1,!0),this._onDidCancel.fire()}dispose(){if(!!this.doc){this._onDidCancel.dispose();for(let e of this.disposables)e.dispose();this.ranges=[],this.doc=null,this.textDocument=null}}get buffer(){return this.nvim.createBuffer(this.doc.bufnr)}getTextRange(e,t){let{ranges:i}=this;if(t.indexOf(` +`)!==-1||e.start.line!=e.end.line)return null;i.sort((n,o)=>n.line!=o.line?n.line-o.line:n.currRange.start.character-o.currRange.start.character);for(let n=0;n{s.add(s.text.length,i)});else{let s=t.start.character-e.currRange.start.character;n.forEach(a=>{a.add(Math.min(a.text.length,s),i)})}else{let o=t.end.character-t.start.character;if(e.currRange.end.character==t.end.character)if(e.currRange.start.character==t.start.character)if(i.includes(e.text)){let a=i.indexOf(e.text),l=a==0?"":i.slice(0,a),u=i.slice(a+e.text.length);l&&n.forEach(c=>c.add(0,l)),u&&n.forEach(c=>c.add(c.text.length,u))}else if(e.text.includes(i)){let a=e.text.indexOf(i),l=e.text.length-(a+i.length);a!=0&&n.forEach(u=>u.replace(0,a)),l>0&&n.forEach(u=>u.replace(u.text.length-l,u.text.length))}else this.cancel();else n.forEach(a=>{let l=a.text.length;a.replace(Math.max(0,l-o),l,i)});else{let a=t.start.character-e.currRange.start.character;n.forEach(l=>{let u=l.text.length;l.replace(a,Math.min(a+o,u),i)})}}}addRange(e,t){if(this.changed){C.showMessage("Can't add range after range change.");return}let{ranges:i}=this,n=i.findIndex(o=>ql(o.range,e));if(n!==-1){i.splice(n,1);for(let o of i)o.line==e.start.line&&o.start>e.start.character&&(o.preCount=o.preCount-1)}else{let o=0,s=0,{line:a}=e.start;for(let u of i){if(u.line>a||u.line==a&&u.start>e.end.character)break;u.line==a&&o++,s++}let l=new WC(a,e.start.character,e.end.character,t,o);i.splice(s,0,l);for(let u of i)u.line==e.start.line&&u.start>e.start.character&&(u.preCount=u.preCount+1)}this.ranges.length==0?this.cancel():this.doHighlights()}async applySingleEdit(e,t){let{range:i,newText:n}=t,{doc:o}=this;if(this.adjustRanges(e,i,n),this.ranges.length==1){this.doHighlights();return}let s=this.ranges.map(d=>d.textEdit),l=kt.applyEdits(this.textDocument,s).split(` +`),u=new Set,c=[];for(let d of this.ranges)u.has(d.line)||(u.add(d.line),c.push([d.line,l[d.line]]));let{nvim:f}=this;this.changing=!0,await o.changeLines(c),this.changing=!1,this.activated&&(this.ranges.forEach(d=>{d.sync()}),this.textDocument=this.doc.textDocument),f.pauseNotification();let{cursor:p}=A;if(e.preCount>0&&p.bufnr==o.bufnr&&e.line+1==p.lnum){let d=e.preCount*(n.length-(i.end.character-i.start.character));f.call("cursor",[p.lnum,p.col+d],!0)}this.doHighlights(),f.resumeNotification(!1,!0)}applyComposedEdit(e,t){let{range:i,newText:n}=t,{ranges:o}=this,s=kt.create("file:///1","",0,e),a=[],l=Nu.default(e,n),u=0;for(let c=0;cc.newText.includes(` +`)||c.range.start.line!=c.range.end.line)){this.cancel();return}if(a.length==o.length){let c;for(let f=0;f{t.affectsConfiguration("cursors")&&this.loadConfig()},null,this.disposables),A.on("BufUnload",t=>{let i=this.getSession(t);!i||(i.dispose(),this.sessionsMap.delete(t))},null,this.disposables)}loadConfig(){let e=b.getConfiguration("cursors");this.config={nextKey:e.get("nextKey",""),previousKey:e.get("previousKey",""),cancelKey:e.get("cancelKey","")}}getSession(e){return this.sessionsMap.get(e)}async isActivated(){let e=await this.nvim.call("bufnr",["%"]);return this.sessionsMap.get(e)!=null}async select(e,t,i){let n=b.getDocument(e);if(!n||!n.attached){C.showMessage(`buffer ${e} not attached.`);return}let{nvim:o}=this,s=this.createSession(n),a=await C.getCursorPosition(),l;if(t=="operator"){await o.command(`normal! ${i=="line"?"'[":"`["}`);let u=await C.getCursorPosition();await o.command(`normal! ${i=="line"?"']":"`]"}`);let c=await C.getCursorPosition();await C.moveTo(a);let f=Me(u,c);if(f==0)return;f>=0&&([u,c]=[c,u]);let p=n.getline(c.line);c.character=u.length?l=$u.Range.create(a.line,u.length-1,a.line,u.length):l=$u.Range.create(a.line,a.character,a.line,a.character+1),s.addRange(l,u.slice(l.start.character,l.end.character))}else if(t=="range"){await o.call("eval",'feedkeys("\\", "in")');let u=await b.getSelectedRange(i,n);if(!u||Me(u.start,u.end)==0)return;let c=i==""?S9(n,u):HC(n,u);for(let f of c){let p=n.textDocument.getText(f);s.addRange(f,p)}}else{C.showMessage(`${t} not supported`,"error");return}(t=="word"||t=="position")&&await o.command(`silent! call repeat#set("\\(coc-cursors-${t})", -1)`)}createSession(e){let t=this.getSession(e.bufnr);return t||(t=new C9(this.nvim,e,this.config),this.sessionsMap.set(e.bufnr,t),t.onDidCancel(()=>{t.dispose(),this.sessionsMap.delete(e.bufnr)}),t)}async addRanges(e){let{nvim:t}=this,i=await t.call("bufnr",["%"]),n=b.getDocument(i);return!n||!n.attached?(C.showMessage("Document not attached","error"),!1):this.createSession(n).addRanges(e)}reset(){for(let e of this.sessionsMap.values())e.cancel();this.sessionsMap.clear()}dispose(){for(let e of this.sessionsMap.values())e.dispose();this.sessionsMap.clear();for(let e of this.disposables)e.dispose()}},_9=VC;var Ue=S(W());var KC=S(Gr()),JC=S(W());var ube=j()("codelens-buffer"),YC=class{constructor(e,t,i){this.nvim=e;this.bufnr=t;this.config=i;this._disposed=!1;this.fetchCodelenses=KC.default(()=>{this._fetchCodeLenses().logError()},global.hasOwnProperty("__TEST__")?10:100),this.resolveCodeLens=KC.default(()=>{this._resolveCodeLenses().logError()},global.hasOwnProperty("__TEST__")?10:100),this.forceFetch().logError()}async forceFetch(){this.fetchCodelenses.clear(),await this._fetchCodeLenses()}get textDocument(){var e;return(e=b.getDocument(this.bufnr))==null?void 0:e.textDocument}get hasProvider(){let{textDocument:e}=this;return e?U.hasProvider("codeLens",e):!1}async _fetchCodeLenses(){if(!this.config.enabled||!this.hasProvider)return;let{textDocument:e}=this,t=e.version;if(this.codeLenses&&this.codeLenses.codeLenses.length>0&&t==this.codeLenses.version){await this._resolveCodeLenses(!0)||this.clear();return}this.cancel();let n=(this.tokenSource=new JC.CancellationTokenSource).token,o=await U.getCodeLens(e,n);this.tokenSource=void 0,!n.isCancellationRequested&&(this.resolveCodeLens.clear(),Array.isArray(o)&&(this.codeLenses={version:t,codeLenses:o},await this._resolveCodeLenses(!0)||this.clear()))}async _resolveCodeLenses(e=!1){if(!this.config.enabled||!this.codeLenses||this._disposed)return!1;let{codeLenses:t,version:i}=this.codeLenses,[n,o,s]=await this.nvim.eval("[bufnr('%'),line('w0'),line('w$')]");if(!this.textDocument||this.textDocument.version!=i||n!=this.bufnr||(t=t.filter(f=>{let p=f.range.start.line+1;return p>=o&&p<=s}),e||(t=t.filter(f=>f.command==null)),!t.length))return!1;let a=new JC.CancellationTokenSource,l=a.token,u=setTimeout(()=>{a.cancel()},1e3);if(await Promise.all(t.map(f=>U.resolveCodeLens(f,l))),clearTimeout(u),this.tokenSource=void 0,l.isCancellationRequested||this._disposed)return!1;this.srcId=await this.nvim.createNamespace("coc-codelens"),this.nvim.pauseNotification(),e&&this.clear(),this.setVirtualText(t);let c=await this.nvim.resumeNotification();return Array.isArray(c)&&c[1]!=null?(ube.error("Error on resolve codeLens",c[1][2]),!1):!0}setVirtualText(e){if(e.length==0)return;let t=new Map;for(let i of e){let{range:n,command:o}=i;if(!o)continue;let{line:s}=n.start;t.has(s)?t.get(s).push(i):t.set(s,[i])}for(let i of t.keys()){let o=t.get(i).map(l=>l.command);o=o.filter(l=>l&&l.title);let s=[],a=o.length;for(let l=0;l=0;a--)if(i.has(a)){n=i.get(a);break}if(!n){C.showMessage("No codeLenses available","warning");return}let o=n.map(a=>a.command);if(o=o.filter(a=>a.command!=null&&a.command!=""),o.length==0)C.showMessage("CodeLenses command not found","warning");else if(o.length==1)me.execute(o[0]);else{let a=await C.showMenuPicker(o.map(l=>l.title));if(a==-1)return;me.execute(o[a])}}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose(),this.tokenSource=null)}onChange(){!this.config.enabled||(this.cancel(),this.resolveCodeLens.clear())}dispose(){this._disposed=!0,this.codeLenses=void 0,this.cancel(),this.fetchCodelenses.clear(),this.resolveCodeLens.clear()}},P9=YC;var T9e=j()("codelens"),XC=class{constructor(e){this.nvim=e;this.disposables=[];this.setConfiguration(),b.onDidChangeConfiguration(i=>{this.setConfiguration(i)},null,this.disposables),this.buffers=b.registerBufferSync(i=>{if(i.buftype=="")return new P9(e,i.bufnr,this.config)}),A.on("ready",()=>{this.checkProvider()},null,this.disposables),A.on("CursorMoved",i=>{let n=this.buffers.getItem(i);n&&n.resolveCodeLens()},null,this.disposables);let t=async i=>{let n=this.buffers.getItem(i);n&&await n.forceFetch()};A.on("CursorHold",t,this,this.disposables)}checkProvider(){for(let e of this.buffers.items)e.hasProvider&&e.fetchCodelenses()}setConfiguration(e){if(e&&!e.affectsConfiguration("codeLens"))return;let t=b.getConfiguration("codeLens"),i=this.nvim.hasFunction("nvim_buf_set_virtual_text")&&t.get("enable",!1);if(e&&i!=this.config.enabled)for(let n of this.buffers.items)i?n.forceFetch().logError():n.clear();this.config=Object.assign(this.config||{},{enabled:i,separator:t.get("separator","\u2023"),subseparator:t.get("subseparator"," ")})}async doAction(){let{nvim:e}=this,t=await e.call("bufnr","%"),i=await e.call("line",".")-1,n=this.buffers.getItem(t);await(n==null?void 0:n.doAction(i))}dispose(){this.buffers.dispose(),z(this.disposables)}},T9=XC;var JK=S(W());var Sy=S(W());var BK=S($K());BK.default.shim();function jK(r,e){if(!e.length)return null;let t=e.length-1,i=e[t];if(i.text==r)return i;for(;t>=0;){let n=e[t];if(n.text==r)return n;t--}return null}function yP(r,e){let t=r.selectionRange,i=e.selectionRange;return t.start.linei.start.line?1:t.start.character-i.start.character}function bP(r,e,t){let{name:i,selectionRange:n,kind:o,children:s,range:a}=e,{start:l}=n;if(r.push({col:l.character+1,lnum:l.line+1,text:i,level:t,kind:_n(o),range:a,selectionRange:n}),s&&s.length){s.sort(yP);for(let u of s)bP(r,u,t+1)}}function UK(r,e){let t=r.location.range.start,i=e.location.range.start,n=t.line-i.line;return n==0?t.character-i.character:n}function K0e(r){return r&&!r.hasOwnProperty("location")}function wP(r){return K0e(r[0])}function WK(r){return!!(Sy.MarkupContent.is(r)&&r.kind==Sy.MarkupKind.Markdown)}function Vu(r,e,t,i=!1){let n=e.trim();!n.length||(i&&t!=="markdown"&&(n="``` "+t+` +`+n+"\n```"),r.push({content:n,filetype:t}))}async function mt(r){let{changedtick:e}=r;await r.patchChange(),e!=r.changedtick&&await He(50)}function yd(r){let e=vd(r);return`${xP(e.red.toString(16))}${xP(e.green.toString(16))}${xP(e.blue.toString(16))}`}function xP(r){return r.length==1?`0${r}`:r}function vd(r){let{red:e,green:t,blue:i}=r;return{red:Math.round(e*255),green:Math.round(t*255),blue:Math.round(i*255)}}function HK(r){let e=[r.red,r.green,r.blue],t=[];for(let n=0;n{this.doHighlight().catch(o=>{VK.error("Error on color highlight:",o.stack)})},global.hasOwnProperty("__TEST__")?10:500)}onChange(){this.cancel(),this.highlight()}get buffer(){return this.nvim.createBuffer(this.bufnr)}get colors(){return this._colors}hasColor(){return this._colors.length>0}setState(e){this.enabled=e,e?this.highlight():this.clearHighlight()}async doHighlight(){let e=b.getDocument(this.bufnr);if(!(!e||!this.enabled))try{this.tokenSource=new GK.CancellationTokenSource;let{token:t}=this.tokenSource;if(this.version&&e.version==this.version)return;let{version:i}=e,n;if(n=await U.provideDocumentColors(e.textDocument,t),n=n||[],t.isCancellationRequested)return;this.version=i,await this.addHighlight(n,t)}catch(t){VK.error("Error on highlight:",t)}}async addHighlight(e,t){if(e=e||[],Ne(this._colors,e))return;let{nvim:i}=this;this._colors=e;let n=oj(e,100);i.pauseNotification(),this.buffer.clearNamespace("color"),this.defineColors(e),i.resumeNotification(!1,!0);for(let o of n){if(t.isCancellationRequested){this._colors=[];return}i.pauseNotification();let s=this.getColorRanges(o);for(let a of s)this.highlightColor(a.ranges,a.color);i.resumeNotification(!1,!0)}b.isVim&&this.nvim.command("redraw",!0)}highlightColor(e,t){let{red:i,green:n,blue:o}=vd(t),s=`BG${yd(t)}`;this.buffer.highlightRanges("color",s,e)}defineColors(e){for(let t of e){let i=yd(t.color);this.usedColors.has(i)||(this.nvim.command(`hi BG${i} guibg=#${i} guifg=#${HK(t.color)?"ffffff":"000000"}`,!0),this.usedColors.add(i))}}getColorRanges(e){let t=[];for(let i of e){let{color:n,range:o}=i,s=t.findIndex(a=>Ne(vd(a.color),vd(n)));s==-1?t.push({color:n,ranges:[o]}):t[s].ranges.push(o)}return t}clearHighlight(){this.highlight.clear(),this._colors=[],this.version=null,this.buffer.clearNamespace("color")}hasColorAtPostion(e){let{colors:t}=this;return t.some(i=>Wt(e,i.range)==0)}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}dispose(){this.highlight.clear(),this.cancel()}},KK=DP;var AGe=j()("colors"),SP=class{constructor(e){this.nvim=e;this._enabled=!0;this.disposables=[];let t=b.getConfiguration("coc.preferences");this._enabled=t.get("colorSupport",!0),b.isVim&&!b.env.textprop&&(this._enabled=!1);let i=new Set;this.highlighters=b.registerBufferSync(n=>{let o=new KK(this.nvim,n.bufnr,this._enabled,i);return o.highlight(),o}),ge.onDidActiveExtension(()=>{this.highlightAll()},null,this.disposables),b.onDidChangeConfiguration(async n=>{if(!(b.isVim&&!b.env.textprop)&&n.affectsConfiguration("coc.preferences.colorSupport")){let s=b.getConfiguration("coc.preferences").get("colorSupport",!0);if(s!=this._enabled){this._enabled=s;for(let a of this.highlighters.items)a.setState(s)}}},null,this.disposables)}async pickPresentation(){let e=await this.currentColorInfomation();if(!e)return C.showMessage("Color not found at current position","warning");let t=await b.document,i=new JK.CancellationTokenSource,n=await U.provideColorPresentations(e,t.textDocument,i.token);if(!n||n.length==0)return;let o=await C.showMenuPicker(n.map(c=>c.label),"choose color:");if(o==-1)return;let s=n[o],{textEdit:a,additionalTextEdits:l,label:u}=s;a||(a={range:e.range,newText:u}),await t.applyEdits([a]),l&&await t.applyEdits(l)}async pickColor(){let e=await this.currentColorInfomation();if(!e)return C.showMessage("Color not found at current position","warning");let{color:t}=e,i=[(t.red*255).toFixed(0),(t.green*255).toFixed(0),(t.blue*255).toFixed(0)],n=await this.nvim.call("coc#util#pick_color",[i]);if(n===!1)return;if(!n||n.length!=3){C.showMessage("Failed to get color","warning");return}let o=yd({red:n[0]/65535,green:n[1]/65535,blue:n[2]/65535,alpha:1});await(await b.document).applyEdits([{range:e.range,newText:`#${o}`}])}get enabled(){return this._enabled}clearHighlight(e){let t=this.highlighters.getItem(e);!t||t.clearHighlight()}hasColor(e){let t=this.highlighters.getItem(e);return t?t.hasColor():!1}hasColorAtPostion(e,t){let i=this.highlighters.getItem(e);return i?i.hasColorAtPostion(t):!1}highlightAll(){for(let e of this.highlighters.items)e.highlight()}async doHighlight(e){let t=this.highlighters.getItem(e);!t||await t.doHighlight()}async currentColorInfomation(){let e=await this.nvim.call("bufnr","%"),t=this.highlighters.getItem(e);if(!t)return null;let i=await C.getCursorPosition();for(let n of t.colors){let{range:o}=n,{start:s,end:a}=o;if(i.line==s.line&&i.character>=s.character&&i.character<=a.character)return n}return null}dispose(){this.highlighters.dispose(),z(this.disposables)}},YK=SP;var sn=S(W());var EP=j()("handler-format"),XK=new Map([["<",">"],[">","<"],["{","}"],["[","]"],["(",")"]]),CP=class{constructor(e){this.nvim=e;this.disposables=[];this.requestStatusItem=C.createStatusBarItem(0,{progress:!0}),this.loadPreferences(),b.onDidChangeConfiguration(this.loadPreferences,this,this.disposables),b.onWillSaveTextDocument(s=>{let{languageId:a}=s.document,l=this.preferences.formatOnSaveFiletypes;if(l.includes(a)||l.some(u=>u==="*")){let u=async()=>{if(!U.hasFormatProvider(s.document)){EP.warn(`Format provider not found for ${s.document.uri}`);return}let c=await b.getFormatOptions(s.document.uri),f=new sn.CancellationTokenSource,p=setTimeout(()=>{f.cancel()},1e3),d=await U.provideDocumentFormattingEdits(s.document,c,f.token);return clearTimeout(p),d};s.waitUntil(u())}},null,this.disposables),A.on(["CursorMoved","CursorMovedI","InsertEnter","TextChangedI","TextChangedP","TextChanged"],()=>{this.requestTokenSource&&(this.requestTokenSource.cancel(),this.requestTokenSource=null)},null,this.disposables),A.on("Enter",async s=>{let{bracketEnterImprove:a}=this.preferences;if(await this.tryFormatOnType(` +`,s),a){let l=await e.call("line",".")-1,u=b.getDocument(s);if(!u)return;await u.patchChange();let c=u.getline(l-1),f=u.getline(l),p=c[c.length-1];if(p&&XK.has(p)){let d=f.trim()[0];if(d&&XK.get(p)==d){let h=[],m=await b.getFormatOptions(u.uri),y=m.insertSpaces?" ".repeat(m.tabSize):" ",v=f.match(/^\s*/)[0],x=sn.Position.create(l-1,c.length);if(u.filetype=="vim"){let w=` +`+v+y;h.push({range:sn.Range.create(l,v.length,l,v.length),newText:" \\ "}),w=w+"\\ ",h.push({range:sn.Range.create(x,x),newText:w}),await u.applyEdits(h),await C.moveTo(sn.Position.create(l,w.length-1))}else await e.eval(`feedkeys("\\O", 'in')`)}}}},null,this.disposables);let t,i;A.on("InsertCharPre",async()=>{i=Date.now()},null,this.disposables),A.on("TextChangedI",async(s,a)=>{if(t=Date.now(),!i||t-i>300)return;i=null;let l=b.getDocument(s);if(!l)return;let u=a.pre[a.pre.length-1];!u||!U.hasProvider("onTypeEdit",l.textDocument)||await this.tryFormatOnType(u,s)},null,this.disposables);let n,o;A.on("InsertEnter",s=>{n=s,o=Date.now()}),A.on("TextChangedI",async(s,a)=>{!this.preferences.formatOnType&&!/^\s*$/.test(a.pre)||n!=s||!o||Date.now()-o>30||await this.tryFormatOnType(` +`,s,!0)})}loadPreferences(e){if(!e||e.affectsConfiguration("coc.preferences")){let t=b.getConfiguration("coc.preferences");this.preferences={formatOnType:t.get("formatOnType",!1),formatOnSaveFiletypes:t.get("formatOnSaveFiletypes",[]),formatOnTypeFiletypes:t.get("formatOnTypeFiletypes",[]),bracketEnterImprove:t.get("bracketEnterImprove",!0)}}}async withRequestToken(e,t){this.requestTokenSource&&(this.requestTokenSource.cancel(),this.requestTokenSource.dispose());let i=this.requestStatusItem;this.requestTokenSource=new sn.CancellationTokenSource;let{token:n}=this.requestTokenSource;n.onCancellationRequested(()=>{i.text=`${e} request canceled`,i.isProgress=!1,i.hide()}),i.isProgress=!0,i.text=`requesting ${e}`,i.show();let o;try{o=await Promise.resolve(t(n))}catch(s){C.showMessage(s.message,"error"),EP.error(`Error on ${e}`,s)}return this.requestTokenSource&&(this.requestTokenSource.dispose(),this.requestTokenSource=void 0),n.isCancellationRequested?null:(i.hide(),o==null&&EP.warn(`${e} provider not found!`),o)}async tryFormatOnType(e,t,i=!1){if(!e||IB(e)||!this.preferences.formatOnType||Ft.getSession(t)!=null)return;let n=b.getDocument(t);if(!n||!n.attached||n.isCommandLine)return;let o=this.preferences.formatOnTypeFiletypes;if(o.length&&!o.includes(n.filetype)||!U.hasOnTypeProvider(e,n.textDocument))return;let s,a=await this.withRequestToken("onTypeFormat ",async c=>{s=await C.getCursorPosition();let f=n.getline(s.line-1);if(i&&/^\s*$/.test(f))return;let p=i?{line:s.line-1,character:f.length}:s;return await mt(n),await U.provideDocumentOnTypeEdits(e,n.textDocument,p,c)});if(!a||!a.length)return;let l=$l(s,a);await n.applyEdits(a);let u=l?sn.Position.create(s.line+l.line,s.character+l.character):null;u&&!i&&await C.moveTo(u)}async documentFormat(e){await mt(e);let t=await b.getFormatOptions(e.uri),i=await this.withRequestToken("format",n=>U.provideDocumentFormattingEdits(e.textDocument,t,n));return i&&i.length>0?(await e.applyEdits(i),!0):!1}async documentRangeFormat(e,t){await mt(e);let i;if(t){if(i=await b.getSelectedRange(t,e),!i)return-1}else{let[s,a,l]=await this.nvim.eval("[v:lnum,v:count,mode()]");if(a==0||l=="i"||l=="R")return-1;i=sn.Range.create(s-1,0,s-1+a,0)}let n=await b.getFormatOptions(e.uri),o=await this.withRequestToken("format",s=>U.provideDocumentRangeFormattingEdits(e.textDocument,i,n,s));return o&&o.length>0?(await e.applyEdits(o),0):-1}dispose(){z(this.disposables)}},ZK=CP;var bd=S(W());var J0e=j()("documentHighlight"),_P=class{constructor(e){this.nvim=e;this.disposables=[];this.highlights=new Map;A.on(["TextChanged","TextChangedI","CursorMoved","CursorMovedI"],()=>{this.cancel(),this.clearHighlights()},null,this.disposables)}clearHighlights(){if(this.highlights.size==0)return;let{nvim:e}=b;for(let t of this.highlights.keys())e.createWindow(t).clearMatchGroup("^CocHighlight");this.highlights.clear()}async highlight(){let{nvim:e}=this;this.cancel();let[t,i,n]=await e.eval("[bufnr('%'),win_getid(),get(b:,'coc_cursors_activated',0)]"),o=b.getDocument(t);if(!o||!o.attached||!U.hasProvider("documentHighlight",o.textDocument)||n)return;let s=await C.getCursorPosition(),a=await this.getHighlights(o,s);if(!a)return;let l={};for(let f of a){if(!f.range)continue;let p=f.kind==bd.DocumentHighlightKind.Text?"CocHighlightText":f.kind==bd.DocumentHighlightKind.Read?"CocHighlightRead":"CocHighlightWrite";l[p]=l[p]||[],l[p].push(f.range)}let u=e.createWindow(i);e.pauseNotification(),u.clearMatchGroup("^CocHighlight");for(let f of Object.keys(l))u.highlightRanges(f,l[f],-1,!0);b.isVim&&e.command("redraw",!0);let c=this.nvim.resumeNotification();Array.isArray(c)&&c[1]!=null?J0e.error("Error on highlight",c[1][2]):this.highlights.set(i,a)}hasHighlights(e){return this.highlights.get(e)!=null}async getHighlights(e,t){if(!e||!e.attached||e.isCommandLine)return null;let n=e.getline(t.line)[t.character];if(!n||!e.isWord(n))return null;try{this.tokenSource=new bd.CancellationTokenSource,e.forceSync();let{token:o}=this.tokenSource,s=await U.getDocumentHighLight(e.textDocument,t,o);return this.tokenSource=null,o.isCancellationRequested?null:s}catch(o){return null}}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose(),this.tokenSource=null)}dispose(){this.highlights.clear(),this.cancel(),z(this.disposables)}},QK=_P;var Yu=S(W());var eJ=S(require("child_process")),tJ=S(require("events")),rJ=S(require("path")),iJ=S(require("readline")),nJ=S(jn()),oJ=S(El());var Y0e=j()("handler-search"),X0e=["--color","ansi","--colors","path:fg:black","--colors","line:fg:green","--colors","match:fg:red","--no-messages","--heading","-n"],Z0e="",sJ=class extends tJ.EventEmitter{start(e,t,i){this.process=eJ.spawn(e,t,{cwd:i}),this.process.on("error",c=>{this.emit("error",c.message)});let n=iJ.default.createInterface(this.process.stdout),o,s,a=[],l=[],u=!0;n.on("line",c=>{if(c.includes(Z0e)){let f=Nf(c);if(f[0].foreground=="black"){s={filepath:rJ.default.join(i,f[0].text),ranges:[]};return}if(f[0].foreground=="green"){let d=parseInt(f[0].text,10)-1,h=f[0].text.length+1;u&&(o=d,u=!1);let m="";for(let v of f){if(v.foreground=="red"){let x=d-o,w=m.length-h;l.push(nJ.Range.create(x,w,x,w+v.text.length))}m+=v.text}let y=m.slice(h);a.push(y)}}else{let f=c.trim().length==0;if(s&&(f||c.trim()=="--")){let p={lines:a,highlights:l,start:o,end:o+a.length};s.ranges.push(p)}f&&(this.emit("item",s),s=null),a=[],l=[],u=!0}}),n.on("close",()=>{if(s){if(a.length){let c={lines:a,highlights:l,start:o,end:o+a.length};s.ranges.push(c)}this.emit("item",s)}a=l=s=null,this.emit("end")})}dispose(){this.process&&this.process.kill()}},PP=class{constructor(e,t="rg"){this.nvim=e;this.cmd=t}run(e,t,i){let{nvim:n,cmd:o}=this,{afterContext:s,beforeContext:a}=i.config,l=["-A",s.toString(),"-B",a.toString()].concat(X0e,e);l.push("--","./");try{o=oJ.default.sync(o)}catch(m){return C.showMessage(`Please install ripgrep and make sure ${this.cmd} is in your $PATH`,"error"),Promise.reject(m)}this.task=new sJ,this.task.start(o,l,t);let u=new ar,c=0,f=0,p=Date.now(),d=[],h=async()=>{if(d.length==0)return;let m=d.slice();d=[];let y=await u.acquire();try{await i.addFileItems(m)}catch(v){Y0e.error(v)}y()};return new Promise((m,y)=>{let v=setInterval(h,300);this.task.on("item",async x=>{c++,f=f+x.ranges.reduce((w,E)=>w+E.highlights.length,0),d.push(x)}),this.task.on("error",x=>{clearInterval(v),C.showMessage(`Error on command "${o}": ${x}`,"error"),this.task=null,y(new Error(x))}),this.task.on("end",async()=>{clearInterval(v);try{await h(),(await u.acquire())(),this.task.removeAllListeners(),this.task=null;let w=i.buffer;if(w){if(n.pauseNotification(),c==0)w.setLines(["No match found"],{start:1,end:2,strictIndexing:!1},!0),w.addHighlight({line:1,srcId:-1,colEnd:-1,colStart:0,hlGroup:"Error"}).logError(),w.setOption("modified",!1,!0);else{let E=new ss;E.addText("Files","MoreMsg"),E.addText(": "),E.addText(`${c} `,"Number"),E.addText("Matches","MoreMsg"),E.addText(": "),E.addText(`${f} `,"Number"),E.addText("Duration","MoreMsg"),E.addText(": "),E.addText(`${Date.now()-p}ms`,"Number"),E.render(w,1,2)}w.setOption("modified",!1,!0),await n.resumeNotification(!1,!0)}}catch(x){y(x);return}m()})})}},aJ=PP;var Ku=S(Bl()),wd=S(require("path")),Ey=S(W());var lJ=j()("handler-refactorBuffer"),Ju="\u3000",TP=class{constructor(e,t,i,n,o){this.bufnr=e;this.srcId=t;this.nvim=i;this.config=n;this.opts=o;this.mutex=new ar;this._disposed=!1;this.disposables=[];this._fileItems=[];this.matchIds=new Set;this.changing=!1;this.disposables.push(b.registerLocalKeymap("n","",this.splitOpen.bind(this),!0)),b.onDidChangeTextDocument(this.onDocumentChange,this,this.disposables)}get fileItems(){return this._fileItems}onChange(e){if(this.changing)return;let t=this.document,{nvim:i,_fileItems:n}=this;if(!n.length)return;let o=e.contentChanges[0];if(!("range"in o))return;let{original:s}=e;if(o.range.end.line<2)return;t.buffer.setOption("modified",!0,!0);let{range:a,text:l}=o,c=l.split(` +`).length-(a.end.line-a.start.line)-1;if(c==0)return;let f=[];if(l.includes("\u3000")){let d=a.start.line,h=Ku.default(s,l),m=0,y=kt.create("file:///1","",0,s);for(let v=0;vy.lnumv+x.delta,0);h.lnum=h.lnum+y,p=!0}}!p||(i.pauseNotification(),this.highlightLineNr(),i.resumeNotification().then(d=>{Array.isArray(d)&&d[1]!=null&&lJ.error("Error on highlightLineNr:",d[1])}).logError())}async onDocumentChange(e){if(e.bufnr==this.bufnr||this.changing)return;let{uri:t}=e.textDocument,{range:i,text:n}=e.contentChanges[0],o=$.parse(t).fsPath,s=this._fileItems.find(u=>u.filepath==o);if(!s)return;let a=n.split(` +`).length-(i.end.line-i.start.line)-1,l=[];for(let u=0;u=c.end))if(i.end.lineu.ranges&&u.ranges.length>0),l.length&&(this.changing=!0,await this.document.applyEdits(l),this.changing=!1),this.nvim.pauseNotification(),this.highlightLineNr(),this.buffer.setOption("modified",!1,!0),await this.nvim.resumeNotification()}async getFileChanges(){if(this._disposed)return[];let e=[],t=await this.buffer.lines;t.push(Ju);let i=[],n,o;for(let s=0;s1){let l=a.match(/^\u3000(.*)/);l&&(n=this.getAbsolutePath(l[1].replace(/\s+$/,"")),o=s+1,i=[])}}else i.push(a)}return e}async splitOpen(){let{nvim:e}=this,i=await e.createWindow(this.opts.fromWinid).valid,n=await e.eval('getline(1,line("."))'),o=n.length;for(let s=0;sd.filepath==f.filepath);p?p.ranges.push(...f.ranges):this._fileItems.push(f)}let o=i.lineCount,s=new ss,a=[];for(let f of e)for(let p of f.ranges){s.addLine(Ju),s.addLine(Ju),p.lnum=o+s.length,s.addText(`${Ye(t,f.filepath)?wd.default.relative(t,f.filepath):f.filepath}`);let d=String(p.start+1).length+String(p.end).length+4;this.srcId||s.addText(" ".repeat(d));let h=0-s.length-o;p.highlights&&a.push(...p.highlights.map(y=>Q0e(y,h)));let{lines:m}=p;m||(m=await this.getLines(f.filepath,p.start,p.end),p.lines=m),s.addLines(m)}let{nvim:l,buffer:u}=this;if(this.changing=!0,l.pauseNotification(),s.render(u,o),this.highlightLineNr(),u.setOption("modified",!1,!0),u.setOption("undolevels",1e3,!0),o==2&&a.length){let f=a[0].start;l.call("coc#util#jumpTo",[f.line,f.character],!0)}b.isVim&&l.command("redraw",!0);let[,c]=await l.resumeNotification();if(c)throw new Error(c[2]);await i.patchChange(),this.changing=!1,await me.executeCommand("editor.action.addRanges",a)}catch(o){this.changing=!1,lJ.error("Error on add file item:",o)}n()}async save(){let{nvim:e}=this,t=this.document,{buffer:i}=t;await t.patchChange();let n=await this.getFileChanges();if(!n)return;n.sort((l,u)=>l.lnum-u.lnum);let o=[],s=new Map;for(let l=0;lm.filepath==c),h=d?d.ranges.find(m=>m.lnum==f):null;if(!h||Ne(h.lines,u.lines)){o.push(l),p&&h&&(h.start=h.start+p,h.end=h.end+p);continue}if(u.start=h.start,u.end=h.end,p!=0&&(h.start=h.start+p),u.lines.length!=h.lines.length){let y=u.lines.length-h.lines.length+p;s.set(c,y),h.end=h.end+y}else h.end=h.end+p;h.lines=u.lines}if(o.length&&(n=n.filter((l,u)=>!o.includes(u))),n.length==0)return C.showMessage("No change.","more"),await i.setOption("modified",!1),!1;let a={};for(let l of n){let u=$.file(l.filepath).toString(),c=a[u]||[];c.push({range:Ey.Range.create(l.start,0,l.end,0),newText:l.lines.join(` +`)+` +`}),a[u]=c}return this.changing=!0,await b.applyEdit({changes:a}),this.changing=!1,e.pauseNotification(),i.setOption("modified",!1,!0),this.config.saveToFile&&e.command("silent noa wa",!0),this.highlightLineNr(),await e.resumeNotification(),!0}getFileRange(e){for(let t of this._fileItems)for(let i of t.ranges)if(i.lnum==e)return i;return null}getLinesRange(e){for(let t of this._fileItems)for(let i of t.ranges)if(i.lnum==e)return[i.start,i.end];return null}async getLines(e,t,i){let n=$.file(e).toString(),o=b.getDocument(n);return o?o.getLines(t,i):await Y3(e,t,i-1)}getAbsolutePath(e){return wd.default.isAbsolute(e)?e:wd.default.join(this.opts.cwd,e)}getFileRangeRange(e,t=!0){let{document:i}=this;if(!i)return null;let{lnum:n}=e;if(!i.getline(n-1).startsWith("\u3000"))return null;let s=t?n:n-1,a=i.lineCount;for(let l=n;l{this.buffers.get(e.bufnr)&&this.buffers.delete(e.bufnr)},null,this.disposables),b.onDidChangeTextDocument(e=>{let t=this.buffers.get(e.bufnr);t&&t.onChange(e)},null,this.disposables)}setConfiguration(e){if(e&&!e.affectsConfiguration("refactor"))return;let t=b.getConfiguration("refactor");this.config=Object.assign(this.config||{},{afterContext:t.get("afterContext",3),beforeContext:t.get("beforeContext",3),openCommand:t.get("openCommand","edit"),saveToFile:t.get("saveToFile",!0)})}getBuffer(e){return this.buffers.get(e)}async search(e){let t=await this.createRefactorBuffer();if(!t)return;let i=await this.nvim.call("getcwd",[]);await new aJ(this.nvim).run(e,i,t)}async createRefactorBuffer(e){let{nvim:t}=this,[i,n]=await t.eval("[win_getid(),getcwd()]"),{openCommand:o}=this.config;t.pauseNotification(),t.command(`${o} ${tSe}${rSe++}`,!0),t.command("setl buftype=acwrite nobuflisted bufhidden=wipe nofen wrap conceallevel=2 concealcursor=n",!0),t.command("setl undolevels=-1 nolist nospell noswapfile foldmethod=expr foldexpr=coc#util#refactor_foldlevel(v:lnum)",!0),t.command("setl foldtext=coc#util#refactor_fold_text(v:foldstart)",!0),t.call("setline",[1,["Save current buffer to make changes",Ju]],!0),t.call("matchadd",["Comment","\\%1l"],!0),t.call("matchadd",["Conceal","^\\%u3000"],!0),t.call("matchadd",["Label","^\\%u3000\\zs\\S\\+"],!0),t.command("setl nomod",!0),e&&t.command(`runtime! syntax/${e}.vim`,!0),t.call("coc#util#do_autocmd",["CocRefactorOpen"],!0);let[,s]=await t.resumeNotification();if(s){eSe.error(s),C.showMessage(`Error on open refactor window: ${s}`,"error");return}let[a,l]=await t.eval('[bufnr("%"),win_getid()]'),u={fromWinid:i,winid:l,cwd:n};await b.document;let c=new uJ(a,this.srcId,this.nvim,this.config,u);return this.buffers.set(a,c),c}async fromLines(e){let t=await this.createRefactorBuffer();return t&&await t.buffer.setLines(e,{start:0,end:-1,strictIndexing:!1}),t}async fromLocations(e,t){if(!e||e.length==0)return null;let i={},n={changes:i};for(let o of e){let s=i[o.uri]||[];s.push({range:o.range,newText:""}),i[o.uri]=s}return await this.fromWorkspaceEdit(n,t)}async fromWorkspaceEdit(e,t){if(!e||iSe(e))return;let i=[],{beforeContext:n,afterContext:o}=this.config,{changes:s,documentChanges:a}=e;if(!s){s={};for(let u of a||[])if(Yu.TextDocumentEdit.is(u)){let{textDocument:c,edits:f}=u;c.uri.startsWith("file:")&&(s[c.uri]=f)}}for(let u of Object.keys(s)){let c=await this.getLineCount(u),f=s[u],p=[],d=null,h=null,m=[];f.sort((y,v)=>y.range.start.line-v.range.start.line);for(let y of f){let{line:v}=y.range.start,x=Math.max(0,v-n);d!=null&&x{if(!this.signaturePosition)return;let o=b.getDocument(i);if(!o)return;let{line:s,character:a}=this.signaturePosition;if(n[0]-1==s){let l=o.getline(n[0]-1),u=ue(l.slice(0,a))+1;if(n[1]>=u)return}this.signatureFactory.close()},null,this.disposables),A.on(["InsertLeave","BufEnter"],()=>{var i;(i=this.tokenSource)==null||i.cancel(),this.signatureFactory.close()},null,this.disposables),A.on(["TextChangedI","TextChangedP"],async()=>{this.config.hideOnChange&&this.signatureFactory.close()},null,this.disposables);let t;A.on("InsertCharPre",async()=>{t=Date.now()},null,this.disposables),A.on("TextChangedI",async(i,n)=>{if(!this.config.trigger||!t||Date.now()-t>300)return;t=null;let o=b.getDocument(i);if(!o||o.isCommandLine||!o.attached)return;let s=n.pre[n.pre.length-1];!s||U.shouldTriggerSignatureHelp(o.textDocument,s)&&await this.triggerSignatureHelp(o,{line:n.lnum-1,character:n.pre.length},!1)},null,this.disposables)}loadConfiguration(e){if(!e||e.affectsConfiguration("signature")){let t=b.getConfiguration("signature"),i=t.get("target","float");i=="float"&&!b.floatSupported&&(i="echo"),this.config={target:i,trigger:t.get("enable",!0),wait:Math.max(t.get("triggerSignatureWait",500),200),maxWindowHeight:t.get("maxWindowHeight",80),maxWindowWidth:t.get("maxWindowWidth",80),preferAbove:t.get("preferShownAbove",!0),hideOnChange:t.get("hideOnTextChange",!1)}}}async triggerSignatureHelp(e,t,i=!0){var p;(p=this.tokenSource)==null||p.cancel();let n=this.tokenSource=new an.CancellationTokenSource,o=n.token;o.onCancellationRequested(()=>{n.dispose(),this.tokenSource=void 0});let{target:s}=this.config,a=this.timer=setTimeout(()=>{n.cancel()},this.config.wait),{changedtick:l}=e;if(await e.patchChange(),l!=e.changedtick&&await He(30),o.isCancellationRequested)return!1;let u=await U.getSignatureHelp(e.textDocument,t,o,{isRetrigger:!1,triggerKind:i?an.SignatureHelpTriggerKind.Invoked:an.SignatureHelpTriggerKind.TriggerCharacter});if(clearTimeout(a),o.isCancellationRequested)return!1;if(!u||u.signatures.length==0)return this.signatureFactory.close(),!1;let{activeSignature:c,signatures:f}=u;if(c){let[d]=f.splice(c,1);d&&f.unshift(d)}s=="echo"?this.echoSignature(u):await this.showSignatureHelp(e,t,u)}async showSignatureHelp(e,t,i){let{signatures:n,activeParameter:o}=i,s=0,a=null,l=n.reduce((d,h,m)=>{var x;let y=null,v=h.label.indexOf("(");if(m==0&&o!=null){let w=(x=h.parameters)==null?void 0:x[o];if(w){let E=h.label.slice(v==-1?0:v);if(a=w.documentation,typeof w.label=="string"){let P=E.slice(0),k=P.match(new RegExp("\\b"+w.label.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b")),_=k?k.index:P.indexOf(w.label);_!=-1&&(y=[_+v,_+w.label.length+v])}else y=w.label}}if(y==null&&(y=[v+1,v+1]),s==0&&(s=y[0]+1),d.push({content:h.label,filetype:e.filetype,active:y}),a){let w=typeof a=="string"?a:a.value;w.trim().length&&d.push({content:w,filetype:pJ(h.documentation)?"markdown":"txt"})}if(m==0&&h.documentation){let{documentation:w}=h,E=typeof w=="string"?w:w.value;E.trim().length&&d.push({content:E,filetype:pJ(h.documentation)?"markdown":"txt"})}return d},[]),u=Ft.getSession(e.bufnr);if(u&&u.isActive){let{value:d}=u.placeholder;d.includes(` +`)||(s+=d.length),this.signaturePosition=an.Position.create(t.line,t.character-d.length)}else this.signaturePosition=t;let{preferAbove:c,maxWindowHeight:f,maxWindowWidth:p}=this.config;await this.signatureFactory.show(l,{maxWidth:p,maxHeight:f,preferTop:c,autoHide:!1,offsetX:s,modes:["i","ic","s"]})}echoSignature(e){var s;let{signatures:t,activeParameter:i}=e,n=b.env.columns;t=t.slice(0,b.env.cmdheight);let o=[];for(let a of t){let l=[],{label:u}=a;u=u.replace(/\n/g," "),u.length>=n-16&&(u=u.slice(0,n-16)+"...");let c=u.indexOf("(");if(c==-1)l=[{text:u,type:"Normal"}];else{l.push({text:u.slice(0,c),type:"Label"});let f=u.slice(c);if(o.length==0&&i!=null){let p=(s=a.parameters)==null?void 0:s[i];if(p){let d,h;if(typeof p.label=="string"){let m=f.slice(0),y=m.match(new RegExp("\\b"+p.label.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b")),v=y?y.index:m.indexOf(p.label);v==-1?l.push({text:f,type:"Normal"}):(d=v,h=v+p.label.length)}else[d,h]=p.label,d=d-c,h=h-c;d!=null&&h!=null&&(l.push({text:f.slice(0,d),type:"Normal"}),l.push({text:f.slice(d,h),type:"MoreMsg"}),l.push({text:f.slice(h),type:"Normal"}))}}else l.push({text:f,type:"Normal"})}o.push(l)}this.nvim.callTimer("coc#util#echo_signatures",[o],!0)}dispose(){z(this.disposables),this.timer&&clearTimeout(this.timer),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose())}},dJ=kP;function pJ(r){return!!(an.MarkupContent.is(r)&&r.kind==an.MarkupKind.Markdown)}var hJ=S(Gr()),uo=S(W());var IP=class{constructor(e){this.nvim=e;this.disposables=[];this.buffers=b.registerBufferSync(t=>{if(t.buftype!="")return;let i=new mJ(t.bufnr);return i.onDidUpdate(async n=>{await A.fire("SymbolsUpdate",[i.bufnr,n])}),i}),A.on("CursorHold",async t=>{!this.functionUpdate||this.buffers.getItem(t)==null||await this.getCurrentFunctionSymbol(t)},null,this.disposables)}get functionUpdate(){return b.getConfiguration("coc.preferences").get("currentFunctionSymbolAutoUpdate",!1)}get labels(){return b.getConfiguration("suggest").get("completionItemKindLabels",{})}async getDocumentSymbols(e){let t=this.buffers.getItem(e);return t==null?void 0:t.getSymbols()}async getCurrentFunctionSymbol(e){e||(e=await this.nvim.call("bufnr",["%"]));let t=await C.getCursorPosition(),i=await this.getDocumentSymbols(e),n=this.nvim.createBuffer(e);if(!i||i.length===0)return n.setVar("coc_current_function","",!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0),"";i=i.filter(s=>["Class","Method","Function","Struct"].includes(s.kind));let o="";for(let s of i.reverse())if(s.range&&Wt(t,s.range)==0&&!s.text.endsWith(") callback")){o=s.text;let a=this.labels[s.kind.toLowerCase()];a&&(o=`${a} ${o}`);break}return this.functionUpdate&&(n.setVar("coc_current_function",o,!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0)),o}async selectSymbolRange(e,t,i){let n=await this.nvim.call("bufnr",["%"]),o=b.getDocument(n);if(!o||!o.attached)return;let s;if(t)s=await b.getSelectedRange(t,o);else{let c=await C.getCursorPosition();s=uo.Range.create(c,c)}let a=await this.getDocumentSymbols(n);if(!a||a.length===0){C.showMessage("No symbols found","warning");return}let l=a.filter(c=>c.kind=="Property");a=a.filter(c=>i.includes(c.kind));let u;for(let c of a.reverse())if(c.range&&!Ne(c.range,s)&&Ji(s,c.range)){u=c.range;break}if(!u){for(let c of l)if(c.range&&!Ne(c.range,s)&&Ji(s,c.range)){u=c.range;break}}if(e&&u){let{start:c,end:f}=u,p=o.getline(c.line+1),d=o.getline(f.line-1);u=uo.Range.create(c.line+1,p.match(/^\s*/)[0].length,f.line-1,d.length)}u&&await b.selectRange(u)}dispose(){this.buffers.dispose(),z(this.disposables)}},gJ=IP,mJ=class{constructor(e){this.bufnr=e;this.disposables=[];this.autoUpdate=!1;this.symbols=[];this._onDidUpdate=new uo.Emitter;this.onDidUpdate=this._onDidUpdate.event;this.fetchSymbols=hJ.default(()=>{this._fetchSymbols().logError()},global.hasOwnProperty("__TEST__")?10:500)}async getSymbols(){let e=b.getDocument(this.bufnr);return e?(e.forceSync(),this.autoUpdate=!0,e.version==this.version?this.symbols:(this.cancel(),await this._fetchSymbols(),this.symbols)):[]}onChange(){this.cancel()}get textDocument(){var e;return(e=b.getDocument(this.bufnr))==null?void 0:e.textDocument}async _fetchSymbols(){let{textDocument:e}=this;if(!e||e.version==this.version)return;let{version:t}=e,i=this.tokenSource=new uo.CancellationTokenSource,{token:n}=i,o=await U.getDocumentSymbol(e,n);if(this.tokenSource=void 0,o==null||n.isCancellationRequested)return;let s=0,a=[],l=null;if(wP(o))o.sort(yP),o.forEach(u=>bP(a,u,s));else{o.sort(UK);for(let u of o){let{name:c,kind:f,location:p,containerName:d}=u;if(!d||!l)s=0;else if(l.containerName==d)s=l.level||0;else{let y=jK(d,a);s=y?y.level+1:0}let{start:h}=p.range,m={col:h.character+1,lnum:h.line+1,text:c,level:s,kind:_n(f),range:p.range,containerName:d};a.push(m),l=m}}this.version=t,this.symbols=a,wP(o)?this._onDidUpdate.fire(o):this._onDidUpdate.fire(o.map(u=>uo.DocumentSymbol.create(u.name,"",u.kind,u.location.range,u.location.range)))}cancel(){this.fetchSymbols.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}dispose(){this.cancel(),this.symbols=void 0,this._onDidUpdate.dispose(),z(this.disposables)}};var vJ=j()("Handler"),FP=class{constructor(e){this.nvim=e;this.documentLines=[];this.selectionRange=null;this.disposables=[];this.getPreferences(),this.requestStatusItem=C.createStatusBarItem(0,{progress:!0}),b.onDidChangeConfiguration(()=>{this.getPreferences()}),this.refactor=new fJ,this.hoverFactory=new mn(e),this.signature=new dJ(e),this.format=new ZK(e),this.symbols=new gJ(e),this.codeLens=new T9(e),this.colors=new YK(e),this.documentHighlighter=new QK(e),A.on(["CursorMoved","CursorMovedI","InsertEnter","InsertSnippet","InsertLeave"],()=>{this.requestTokenSource&&this.requestTokenSource.cancel()},null,this.disposables);let t={onDidChange:null,provideTextDocumentContent:async()=>(e.pauseNotification(),e.command("setlocal conceallevel=2 nospell nofoldenable wrap",!0),e.command("setlocal bufhidden=wipe nobuflisted",!0),e.command("setfiletype markdown",!0),e.command(`if winnr('j') != winnr('k') | exe "normal! z${Math.min(this.documentLines.length,this.preferences.previewMaxHeight)}\\ | endif"`,!0),await e.resumeNotification(),this.documentLines.join(` +`))};this.disposables.push(b.registerTextDocumentContentProvider("coc",t)),this.disposables.push(me.registerCommand("editor.action.pickColor",()=>this.pickColor())),me.titles.set("editor.action.pickColor","pick color from system color picker when possible."),this.disposables.push(me.registerCommand("editor.action.colorPresentation",()=>this.pickPresentation())),me.titles.set("editor.action.colorPresentation","change color presentation."),this.disposables.push(me.registerCommand("editor.action.organizeImport",async i=>{await this.organizeImport(i)})),me.titles.set("editor.action.organizeImport","run organize import code action.")}async organizeImport(e){e||(e=await this.nvim.call("bufnr",["%"]));let t=b.getDocument(e);if(!t||!t.attached)throw new Error(`buffer ${e} not attached`);await mt(t);let i=await this.getCodeActions(t,void 0,[Ue.CodeActionKind.SourceOrganizeImports]);if(i&&i.length){await this.applyCodeAction(i[0]);return}throw new Error("Organize import action not found.")}checkProvier(e,t){if(!U.hasProvider(e,t))throw new Error(`${e} provider not found for current buffer, your language server don't support it.`)}async withRequestToken(e,t,i){this.requestTokenSource&&(this.requestTokenSource.cancel(),this.requestTokenSource.dispose()),this.requestTimer&&clearTimeout(this.requestTimer);let n=this.requestStatusItem;this.requestTokenSource=new Ue.CancellationTokenSource;let{token:o}=this.requestTokenSource;o.onCancellationRequested(()=>{n.text=`${e} request canceled`,n.isProgress=!1,this.requestTimer=setTimeout(()=>{n.hide()},500)}),n.isProgress=!0,n.text=`requesting ${e}`,n.show();let s;try{s=await Promise.resolve(t(o))}catch(a){C.showMessage(a.message,"error"),vJ.error(`Error on ${e}`,a)}return this.requestTokenSource&&(this.requestTokenSource.dispose(),this.requestTokenSource=void 0),o.isCancellationRequested?null:(n.hide(),i&&(!s||Array.isArray(s)&&s.length==0)?(C.showMessage(`${e} not found`,"warning"),null):s)}async getCurrentFunctionSymbol(){let{doc:e}=await this.getCurrentState();return this.checkProvier("documentSymbol",e.textDocument),await this.symbols.getCurrentFunctionSymbol()}async selectSymbolRange(e,t,i){let{doc:n}=await this.getCurrentState();return this.checkProvier("documentSymbol",n.textDocument),await this.symbols.selectSymbolRange(e,t,i)}async getDocumentSymbols(e){let t=b.getDocument(e);if(!t||!t.attached)throw new Error(`buffer ${e} not attached`);return this.checkProvier("documentSymbol",t.textDocument),await this.symbols.getDocumentSymbols(e)}async hasProvider(e){let t=await this.nvim.call("bufnr","%"),i=b.getDocument(t);return i?U.hasProvider(e,i.textDocument):!1}async onHover(e){let{doc:t,position:i,winid:n}=await this.getCurrentState();this.checkProvier("hover",t.textDocument);let o=e!=null?e:this.preferences.hoverTarget;o=="float"&&this.hoverFactory.close(),await mt(t);let s=await this.withRequestToken("hover",l=>U.getHover(t.textDocument,i,l),!0);if(s==null)return!1;let a=s.find(l=>Ue.Range.is(l.range));if(a==null?void 0:a.range){let l=this.nvim.createWindow(n),u=await l.highlightRanges("CocHoverRange",[a.range],99);setTimeout(()=>{u.length&&l.clearMatches(u),b.isVim&&this.nvim.command("redraw",!0)},1e3)}return await this.previewHover(s,o),!0}async getHover(){let e=[],{doc:t,position:i}=await this.getCurrentState();this.checkProvier("hover",t.textDocument),await mt(t);let n=new Ue.CancellationTokenSource,o=await U.getHover(t.textDocument,i,n.token);if(Array.isArray(o))for(let s of o){let{contents:a}=s;Array.isArray(a)?a.forEach(l=>{e.push(typeof l=="string"?l:l.value)}):Ue.MarkupContent.is(a)?e.push(a.value):e.push(typeof a=="string"?a:a.value)}return e=e.filter(s=>s!=null&&s.length>0),e}async gotoDefinition(e){let{doc:t,position:i}=await this.getCurrentState();this.checkProvier("definition",t.textDocument),await mt(t);let n=await this.withRequestToken("definition",o=>U.getDefinition(t.textDocument,i,o),!0);return n==null?!1:(await this.handleLocations(n,e),!0)}async gotoDeclaration(e){let{doc:t,position:i}=await this.getCurrentState();this.checkProvier("declaration",t.textDocument),await mt(t);let n=await this.withRequestToken("declaration",o=>U.getDeclaration(t.textDocument,i,o),!0);return n==null?!1:(await this.handleLocations(n,e),!0)}async gotoTypeDefinition(e){let{doc:t,position:i}=await this.getCurrentState();this.checkProvier("typeDefinition",t.textDocument),await mt(t);let n=await this.withRequestToken("type definition",o=>U.getTypeDefinition(t.textDocument,i,o),!0);return n==null?!1:(await this.handleLocations(n,e),!0)}async gotoImplementation(e){let{doc:t,position:i}=await this.getCurrentState();this.checkProvier("implementation",t.textDocument),await mt(t);let n=await this.withRequestToken("implementation",o=>U.getImplementation(t.textDocument,i,o),!0);return n==null?!1:(await this.handleLocations(n,e),!0)}async gotoReferences(e,t=!0){let{doc:i,position:n}=await this.getCurrentState();this.checkProvier("reference",i.textDocument),await mt(i);let o=await this.withRequestToken("references",s=>U.getReferences(i.textDocument,{includeDeclaration:t},n,s),!0);return o==null?!1:(await this.handleLocations(o,e),!0)}async getWordEdit(){let{doc:e,position:t}=await this.getCurrentState(),i=e.getWordRangeAtPosition(t);if(!i||Gn(i))return null;let n=e.textDocument.getText(i);if(U.hasProvider("rename",e.textDocument)){await mt(e);let s=new Ue.CancellationTokenSource;if(await U.prepareRename(e.textDocument,t,s.token)===!1)return null;let l=await U.provideRenameEdits(e.textDocument,t,n,s.token);if(l)return l}C.showMessage("Rename provider not found, extract word ranges from current buffer","more");let o=e.getSymbolRanges(n);return{changes:{[e.uri]:o.map(s=>({range:s,newText:n}))}}}async rename(e){let{doc:t,position:i}=await this.getCurrentState();this.checkProvier("rename",t.textDocument),await mt(t);let n=this.requestStatusItem;try{let o=new Ue.CancellationTokenSource().token,s=await U.prepareRename(t.textDocument,i,o);if(s===!1)return n.hide(),C.showMessage("Invalid position for rename","warning"),!1;if(o.isCancellationRequested)return!1;let a;if(e||(Ue.Range.is(s)?(a=t.textDocument.getText(s),await C.moveTo(s.start)):s&&typeof s.placeholder=="string"?a=s.placeholder:a=await this.nvim.eval('expand("")'),e=await C.requestInput("New name",a)),!e)return n.hide(),!1;let l=await U.provideRenameEdits(t.textDocument,i,e,o);return o.isCancellationRequested?!1:(n.hide(),l?(await b.applyEdit(l),!0):(C.showMessage("Invalid position for rename","warning"),!1))}catch(o){return n.hide(),C.showMessage(`Error on rename: ${o.message}`,"error"),vJ.error(o),!1}}async documentFormatting(){let{doc:e}=await this.getCurrentState();return this.checkProvier("format",e.textDocument),await this.format.documentFormat(e)}async documentRangeFormatting(e){let{doc:t}=await this.getCurrentState();return this.checkProvier("formatRange",t.textDocument),await this.format.documentRangeFormat(t,e)}async getTagList(){let{doc:e,position:t}=await this.getCurrentState(),i=await this.nvim.call("expand","");if(!i||!U.hasProvider("definition",e.textDocument))return null;let n=new Ue.CancellationTokenSource,o=await U.getDefinition(e.textDocument,t,n.token);return!o||!o.length?null:o.map(s=>{let a=$.parse(s.uri),l=a.scheme=="file"?a.fsPath:a.toString();return{name:i,cmd:`keepjumps ${s.range.start.line+1} | normal ${s.range.start.character+1}|`,filename:l}})}async runCommand(e,...t){if(e){await A.fire("Command",[e]);let i=await me.executeCommand(e,...t);return t.length==0&&await me.addRecent(e),i}else await Kt.start(["commands"])}async getCodeActions(e,t,i){t=t||Ue.Range.create(0,0,e.lineCount,0);let o={diagnostics:St.getDiagnosticsInRange(e.textDocument,t)};i&&Array.isArray(i)&&(o.only=i);let s=await this.withRequestToken("code action",a=>U.getCodeActions(e.textDocument,t,o,a));return!s||s.length==0?[]:(s.sort((a,l)=>a.isPreferred&&!l.isPreferred?-1:l.isPreferred&&!a.isPreferred?1:0),s)}async doCodeAction(e,t){let{doc:i}=await this.getCurrentState(),n;e&&(n=await b.getSelectedRange(e,i)),await mt(i);let o=await this.getCodeActions(i,n,Array.isArray(t)?t:null);if(t&&typeof t=="string"&&(o=o.filter(l=>l.title==t||l.command&&l.command.title==t),o.length==1)){await this.applyCodeAction(o[0]);return}if(!o||o.length==0){C.showMessage(`No${t?" "+t:""} code action available`,"warning");return}let s=this.preferences.floatActions?await C.showMenuPicker(o.map(l=>l.title),"Choose action"):await C.showQuickpick(o.map(l=>l.title)),a=o[s];a&&await this.applyCodeAction(a)}async getCurrentCodeActions(e,t){let{doc:i}=await this.getCurrentState(),n;return e&&(n=await b.getSelectedRange(e,i)),await this.getCodeActions(i,n,t)}async doQuickfix(){let e=await this.getCurrentCodeActions("line",[Ue.CodeActionKind.QuickFix]);return!e||e.length==0?(C.showMessage("No quickfix action available","warning"),!1):(await this.applyCodeAction(e[0]),await this.nvim.command('silent! call repeat#set("\\(coc-fix-current)", -1)'),!0)}async applyCodeAction(e){let{command:t,edit:i}=e;if(i&&await b.applyEdit(i),t)if(me.has(t.command))me.execute(t);else{let n=e.clientId,o=Vt.getService(n),s={command:t.command,arguments:t.arguments};if(o.client){let{client:a}=o;a.sendRequest(Ue.ExecuteCommandRequest.type,s).then(void 0,l=>{C.showMessage(`Execute '${t.command} error: ${l}'`,"error")})}}}async doCodeLensAction(){await this.codeLens.doAction()}async fold(e){let{doc:t,winid:i}=await this.getCurrentState();this.checkProvier("foldingRange",t.textDocument),await mt(t);let n=this.nvim.createWindow(i),[o,s]=await this.nvim.eval("[&foldmethod,&foldlevel]");if(o!="manual")return C.showMessage("foldmethod option should be manual!","warning"),!1;let a=await this.withRequestToken("folding range",l=>U.provideFoldingRanges(t.textDocument,{},l),!0);if(!a)return!1;if(e&&(a=a.filter(l=>l.kind==e)),a.length){a.sort((l,u)=>u.startLine-l.startLine),this.nvim.pauseNotification(),this.nvim.command("normal! zE",!0);for(let l of a){let{startLine:u,endLine:c}=l,f=`${u+1}, ${c+1}fold`;this.nvim.command(f,!0)}return n.setOption("foldenable",!0,!0),n.setOption("foldlevel",s,!0),b.isVim&&this.nvim.command("redraw",!0),await this.nvim.resumeNotification(),!0}return!1}async pickColor(){let{doc:e}=await this.getCurrentState();this.checkProvier("documentColor",e.textDocument),await this.colors.pickColor()}async pickPresentation(){let{doc:e}=await this.getCurrentState();this.checkProvier("documentColor",e.textDocument),await this.colors.pickPresentation()}async highlight(){await this.documentHighlighter.highlight()}async getSymbolsRanges(){let{doc:e,position:t}=await this.getCurrentState();this.checkProvier("documentHighlight",e.textDocument);let i=await this.documentHighlighter.getHighlights(e,t);return i?i.map(n=>n.range):null}async links(){let{doc:e}=await this.getCurrentState();this.checkProvier("documentLink",e.textDocument);let t=await this.withRequestToken("links",n=>U.getDocumentLinks(e.textDocument,n));t=t||[];let i=[];for(let n of t)n.target||(n=await U.resolveDocumentLink(n)),i.push(n);return t}async openLink(){let{doc:e,position:t}=await this.getCurrentState();this.checkProvier("documentLink",e.textDocument);let i=await this.withRequestToken("links",n=>U.getDocumentLinks(e.textDocument,n));if(!i||i.length==0)return!1;for(let n of i)if(Wt(t,n.range)){let{target:o}=n;return o||(n=await U.resolveDocumentLink(n),o=n.target),o?(await b.openResource(o),!0):!1}return!1}async getCommands(){let e=me.commandList,t=[],{titles:i}=me;for(let n of e)t.push({id:n.id,title:i.get(n.id)||""});return t}async showSignatureHelp(){let{doc:e,position:t}=await this.getCurrentState();return U.hasProvider("signature",e.textDocument)?await this.signature.triggerSignatureHelp(e,t):!1}async findLocations(e,t,i,n){let{doc:o,position:s}=await this.getCurrentState();i=i||{},Object.assign(i,{textDocument:{uri:o.uri},position:s});let a=await Vt.sendRequest(e,t,i);a=a||[];let l=[];if(Array.isArray(a))l=a;else if(a.hasOwnProperty("location")&&a.hasOwnProperty("children")){let u=c=>{if(l.push(c.location),c.children&&c.children.length)for(let f of c.children)u(f)};u(a)}await this.handleLocations(l,n)}async handleLocations(e,t){if(!e)return;let n=(Array.isArray(e)?e:[e]).length;if(n!=0)if(n==1&&t!==!1){let o=e[0];if(Ue.LocationLink.is(e[0])){let l=e[0];o=Ue.Location.create(l.targetUri,l.targetRange)}let{uri:s,range:a}=o;await b.jumpTo(s,a.start,t)}else await b.showLocations(e)}async getSelectionRanges(){let{doc:e,position:t}=await this.getCurrentState();this.checkProvier("selectionRange",e.textDocument),await mt(e);let i=await this.withRequestToken("selection ranges",n=>U.getSelectionRanges(e.textDocument,[t],n));return i&&i.length?i:null}async selectRange(e,t){let{nvim:i}=this,{doc:n}=await this.getCurrentState();this.checkProvier("selectionRange",n.textDocument);let o=[];if(!t&&(!this.selectionRange||!e))return;if(e){let u=await b.getSelectedRange(e,n);o.push(u.start,u.end)}else{let u=await C.getCursorPosition();o.push(u)}if(!t){let u=Ue.Range.create(o[0],o[1]),{selectionRange:c}=this;for(;c&&c.parent&&!Ne(c.parent.range,u);)c=c.parent;c&&c.parent&&await b.selectRange(c.range);return}await mt(n);let s=await this.withRequestToken("selection ranges",u=>U.getSelectionRanges(n.textDocument,o,u));if(!s||s.length==0)return;await i.eval("mode()")!="n"&&await i.eval(`feedkeys("\\", 'in')`);let l;if(s.length==1)l=s[0];else if(o.length>1){let u=Ue.Range.create(o[0],o[1]);for(l=s[0];l;){if(Ne(u,l.range)){l=l.parent;continue}if(Wt(o[1],l.range)==0)break;l=l.parent}}!l||(this.selectionRange=s[0],await b.selectRange(l.range))}async codeActionRange(e,t,i){let{doc:n}=await this.getCurrentState();await mt(n);let o=n.getline(t-1),s=Ue.Range.create(e-1,0,t-1,o.length),a=await this.getCodeActions(n,s,i?[i]:null);if(!a||a.length==0){C.showMessage(`No${i?" "+i:""} code action available`,"warning");return}let l=await C.showMenuPicker(a.map(c=>c.title),"Choose action"),u=a[l];u&&await this.applyCodeAction(u)}async doRefactor(){let{doc:e,position:t}=await this.getCurrentState();await mt(e);let i=await this.withRequestToken("refactor",async n=>{let o=await U.prepareRename(e.textDocument,t,n);if(n.isCancellationRequested)return null;if(o===!1)return C.showMessage("Invalid position","warning"),null;let s=await U.provideRenameEdits(e.textDocument,t,"NewName",n);return n.isCancellationRequested?null:s||(C.showMessage("Empty workspaceEdit from language server","warning"),null)});i&&await this.refactor.fromWorkspaceEdit(i,e.filetype)}async saveRefactor(e){await this.refactor.save(e)}async search(e){await this.refactor.search(e)}async previewHover(e,t){let i=[],n=t==="preview";for(let s of e){let{contents:a}=s;if(Array.isArray(a))for(let l of a)typeof l=="string"?Vu(i,l,"markdown",n):Vu(i,l.value,l.language,n);else Ue.MarkedString.is(a)?typeof a=="string"?Vu(i,a,"markdown",n):Vu(i,a.value,a.language,n):Ue.MarkupContent.is(a)&&Vu(i,a.value,WK(a)?"markdown":"txt",n)}if(t=="float"){await this.hoverFactory.show(i,{modes:["n"]});return}let o=i.reduce((s,a)=>{let l=a.content.split(/\r?\n/);return s.length>0&&s.push(""),s.push(...l),s},[]);if(t=="echo"){let s=o.join(` +`).trim();s.length&&await this.nvim.call("coc#util#echo_hover",s)}else this.documentLines=o,await this.nvim.command("noswapfile pedit coc://document")}getPreferences(){let e=b.getConfiguration("coc.preferences"),t=e.get("hoverTarget","float");t=="float"&&!b.floatSupported&&(t="preview"),this.preferences={hoverTarget:t,previewMaxHeight:e.get("previewMaxHeight",12),previewAutoClose:e.get("previewAutoClose",!1),floatActions:e.get("floatActions",!0)}}async getCurrentState(){let{nvim:e}=this,[t,[i,n],o]=await e.eval("[bufnr('%'),coc#util#cursor(),win_getid()]"),s=b.getDocument(t);if(!s||!s.attached)throw new Error(`current buffer ${t} not attached`);return{doc:s,position:Ue.Position.create(i,n),winid:o}}dispose(){this.requestTimer&&(clearTimeout(this.requestTimer),this.requestTimer=void 0),this.refactor.dispose(),this.signature.dispose(),this.symbols.dispose(),this.hoverFactory.dispose(),this.colors.dispose(),this.format.dispose(),this.documentHighlighter.dispose(),z(this.disposables)}},yJ=FP;var Xu=j()("plugin"),OP=class extends bJ.EventEmitter{constructor(e){super();this.nvim=e;this._ready=!1;this.actions=new Map;Object.defineProperty(b,"nvim",{get:()=>this.nvim}),this.cursors=new _9(e),this.addAction("hasProvider",t=>this.handler.hasProvider(t)),this.addAction("getTagList",async()=>await this.handler.getTagList()),this.addAction("hasSelected",()=>cs.hasSelected()),this.addAction("listNames",()=>Kt.names),this.addAction("listDescriptions",()=>Kt.descriptions),this.addAction("listLoadItems",async t=>await Kt.loadItems(t)),this.addAction("search",(...t)=>this.handler.search(t)),this.addAction("cursorsSelect",(t,i,n)=>this.cursors.select(t,i,n)),this.addAction("fillDiagnostics",t=>St.setLocationlist(t)),this.addAction("getConfig",async t=>{let i=await b.document;return b.getConfiguration(t,i?i.uri:void 0)}),this.addAction("rootPatterns",t=>{let i=b.getDocument(t);return i?{buffer:b.getRootPatterns(i,Kr.Buffer),server:b.getRootPatterns(i,Kr.LanguageServer),global:b.getRootPatterns(i,Kr.Global)}:null}),this.addAction("installExtensions",async(...t)=>{await ge.installExtensions(t)}),this.addAction("saveRefactor",async t=>{await this.handler.saveRefactor(t)}),this.addAction("updateExtensions",async t=>{await ge.updateExtensions(t)}),this.addAction("commandList",()=>me.commandList.map(t=>t.id)),this.addAction("openList",async(...t)=>{await this.ready,await Kt.start(t)}),this.addAction("selectSymbolRange",(t,i,n)=>this.handler.selectSymbolRange(t,i,n)),this.addAction("listResume",t=>Kt.resume(t)),this.addAction("listCancel",()=>Kt.cancel(!0)),this.addAction("listPrev",t=>Kt.previous(t)),this.addAction("listNext",t=>Kt.next(t)),this.addAction("listFirst",t=>Kt.first(t)),this.addAction("listLast",t=>Kt.last(t)),this.addAction("sendRequest",(t,i,n)=>Vt.sendRequest(t,i,n)),this.addAction("sendNotification",(t,i,n)=>Vt.sendNotification(t,i,n)),this.addAction("registNotification",(t,i)=>Vt.registNotification(t,i)),this.addAction("doAutocmd",async(t,...i)=>{let n=b.autocmds.get(t);if(n)try{await Promise.resolve(n.callback.apply(n.thisArg,i))}catch(o){Xu.error(`Error on autocmd ${n.event}`,o),C.showMessage(`Error on autocmd ${n.event}: ${o.message}`)}}),this.addAction("updateConfig",(t,i)=>{b.configurations.updateUserConfig({[t]:i})}),this.addAction("snippetNext",async()=>(await Ft.nextPlaceholder(),"")),this.addAction("snippetPrev",async()=>(await Ft.previousPlaceholder(),"")),this.addAction("snippetCancel",()=>{Ft.cancel()}),this.addAction("openLocalConfig",async()=>{await C.openLocalConfig()}),this.addAction("openLog",async()=>{let t=Xu.getLogFile();await b.jumpTo($.file(t).toString())}),this.addAction("attach",()=>b.attach()),this.addAction("detach",()=>b.detach()),this.addAction("doKeymap",async(t,i="",n)=>{let o=b.keymaps.get(t);if(!o)return Xu.error(`keymap for ${t} not found`),this.nvim.command(`silent! unmap ${n.startsWith("{")&&n.endsWith("}")?`<${n.slice(1,-1)}>`:n}`,!0),i;let[s,a]=o,l=await Promise.resolve(s());return a&&await e.command(`silent! call repeat#set("\\(coc-${t})", -1)`),l!=null?l:i}),this.addAction("registExtensions",async(...t)=>{for(let i of t)await ge.loadExtension(i)}),this.addAction("snippetCheck",async(t,i)=>{if(t&&!ge.has("coc-snippets"))return console.error("coc-snippets required for check expand status!"),!1;if(i&&Ft.jumpable())return!0;if(t){let n=ge.getExtensionApi("coc-snippets");if(n&&n.hasOwnProperty("expandable")&&await Promise.resolve(n.expandable()))return!0}return!1}),this.addAction("showInfo",async()=>{this.infoChannel?this.infoChannel.clear():this.infoChannel=C.createOutputChannel("info");let t=this.infoChannel;t.appendLine("## versions"),t.appendLine("");let n=(await this.nvim.call("execute",["version"])).trim().split(/\r?\n/,2)[0].replace(/\(.*\)/,"").trim();t.appendLine("vim version: "+n+`${b.isVim?" "+b.env.version:""}`),t.appendLine("node version: "+process.version),t.appendLine("coc.nvim version: "+this.version),t.appendLine("coc.nvim directory: "+wJ.default.dirname(__dirname)),t.appendLine("term: "+(process.env.TERM_PROGRAM||process.env.TERM)),t.appendLine("platform: "+process.platform),t.appendLine(""),t.appendLine("## Log of coc.nvim"),t.appendLine("");let o=Xu.getLogFile();if(AP.default.existsSync(o)){let s=AP.default.readFileSync(o,{encoding:"utf8"});t.appendLine(s)}t.show()}),this.addAction("findLocations",(t,i,n,o)=>this.handler.findLocations(t,i,n,o)),this.addAction("links",()=>this.handler.links()),this.addAction("openLink",()=>this.handler.openLink()),this.addAction("pickColor",()=>this.handler.pickColor()),this.addAction("colorPresentation",()=>this.handler.pickPresentation()),this.addAction("highlight",async()=>{await this.handler.highlight()}),this.addAction("fold",t=>this.handler.fold(t)),this.addAction("startCompletion",async t=>{await cs.startCompletion(t)}),this.addAction("stopCompletion",()=>{cs.stop(!1)}),this.addAction("sourceStat",()=>Ze.sourceStats()),this.addAction("refreshSource",async t=>{await Ze.refresh(t)}),this.addAction("toggleSource",t=>{Ze.toggleSource(t)}),this.addAction("diagnosticInfo",async()=>{await St.echoMessage()}),this.addAction("diagnosticToggle",()=>{St.toggleDiagnostic()}),this.addAction("diagnosticNext",async t=>{await St.jumpNext(t)}),this.addAction("diagnosticPrevious",async t=>{await St.jumpPrevious(t)}),this.addAction("diagnosticPreview",async()=>{await St.preview()}),this.addAction("diagnosticList",()=>St.getDiagnosticList()),this.addAction("jumpDefinition",t=>this.handler.gotoDefinition(t)),this.addAction("jumpDeclaration",t=>this.handler.gotoDeclaration(t)),this.addAction("jumpImplementation",t=>this.handler.gotoImplementation(t)),this.addAction("jumpTypeDefinition",t=>this.handler.gotoTypeDefinition(t)),this.addAction("jumpReferences",t=>this.handler.gotoReferences(t)),this.addAction("jumpUsed",t=>this.handler.gotoReferences(t,!1)),this.addAction("doHover",t=>this.handler.onHover(t)),this.addAction("getHover",()=>this.handler.getHover()),this.addAction("showSignatureHelp",()=>this.handler.showSignatureHelp()),this.addAction("documentSymbols",async t=>(t||(t=await e.call("bufnr",["%"])),await this.handler.getDocumentSymbols(t))),this.addAction("ensureDocument",async()=>{let t=await b.document;return t&&t.attached}),this.addAction("symbolRanges",()=>this.handler.getSymbolsRanges()),this.addAction("selectionRanges",()=>this.handler.getSelectionRanges()),this.addAction("rangeSelect",(t,i)=>this.handler.selectRange(t,i)),this.addAction("rename",t=>this.handler.rename(t)),this.addAction("getWorkspaceSymbols",async t=>{let i=new xd.CancellationTokenSource;return await U.getWorkspaceSymbols(t,i.token)}),this.addAction("formatSelected",t=>this.handler.documentRangeFormatting(t)),this.addAction("format",()=>this.handler.documentFormatting()),this.addAction("commands",()=>this.handler.getCommands()),this.addAction("services",()=>Vt.getServiceStats()),this.addAction("toggleService",t=>Vt.toggle(t)),this.addAction("codeAction",(t,i)=>this.handler.doCodeAction(t,i)),this.addAction("organizeImport",()=>this.handler.organizeImport()),this.addAction("fixAll",()=>this.handler.doCodeAction(null,[xd.CodeActionKind.SourceFixAll])),this.addAction("doCodeAction",t=>this.handler.applyCodeAction(t)),this.addAction("codeActions",(t,i)=>this.handler.getCurrentCodeActions(t,i)),this.addAction("quickfixes",t=>this.handler.getCurrentCodeActions(t,[xd.CodeActionKind.QuickFix])),this.addAction("codeLensAction",()=>this.handler.doCodeLensAction()),this.addAction("runCommand",(...t)=>this.handler.runCommand(...t)),this.addAction("doQuickfix",()=>this.handler.doQuickfix()),this.addAction("refactor",()=>this.handler.doRefactor()),this.addAction("repeatCommand",()=>me.repeatCommand()),this.addAction("extensionStats",()=>ge.getExtensionStates()),this.addAction("loadedExtensions",()=>ge.loadedExtensions()),this.addAction("watchExtension",t=>ge.watchExtension(t)),this.addAction("activeExtension",t=>ge.activate(t)),this.addAction("deactivateExtension",t=>ge.deactivate(t)),this.addAction("reloadExtension",t=>ge.reloadExtension(t)),this.addAction("toggleExtension",t=>ge.toggleExtension(t)),this.addAction("uninstallExtension",(...t)=>ge.uninstallExtension(t)),this.addAction("getCurrentFunctionSymbol",()=>this.handler.getCurrentFunctionSymbol()),this.addAction("getWordEdit",()=>this.handler.getWordEdit()),this.addAction("addRanges",async t=>{await this.cursors.addRanges(t)}),this.addAction("currentWorkspacePath",()=>b.rootPath),this.addAction("addCommand",t=>{this.addCommand(t)}),this.addAction("selectCurrentPlaceholder",t=>Ft.selectCurrentPlaceholder(!!t)),this.addAction("codeActionRange",(t,i,n)=>this.handler.codeActionRange(t,i,n)),b.onDidChangeWorkspaceFolders(()=>{e.setVar("WorkspaceFolders",b.folderPaths,!0)}),me.init(e,this)}addAction(e,t){if(this.actions.has(e))throw new Error(`Action ${e} already exists`);this.actions.set(e,t)}addCommand(e){let t=`vim.${e.id}`;me.registerCommand(t,async()=>{await this.nvim.command(e.cmd)}),e.title&&me.titles.set(t,e.title)}async init(){let{nvim:e}=this,t=Date.now();try{await ge.init(),await b.init(),U.init();for(let i of b.env.vimCommands)this.addCommand(i);Ft.init(),cs.init(),St.init(),Kt.init(e),e.setVar("coc_workspace_initialized",1,!0),e.setVar("WorkspaceFolders",b.folderPaths,!0),Ze.init(),this.handler=new yJ(e),Vt.init(),await ge.activateExtensions(),b.setupDynamicAutocmd(!0),e.setVar("coc_service_initialized",1,!0),e.call("coc#util#do_autocmd",["CocNvimInit"],!0),this._ready=!0,await A.fire("ready",[]),Xu.info(`coc.nvim ${this.version} initialized with node: ${process.version} after ${Date.now()-t}ms`),this.emit("ready")}catch(i){console.error(`Error on initialize: ${i.stack}`),Xu.error(i.stack)}b.onDidOpenTextDocument(async i=>{!i.uri.endsWith(Gi)||ge.has("coc-json")||C.showMessage("Run :CocInstall coc-json for json intellisense","more")})}get isReady(){return this._ready}get ready(){return this._ready?Promise.resolve():new Promise(e=>{this.once("ready",()=>{e()})})}get version(){return b.version+"-d09f35455b"}hasAction(e){return this.actions.has(e)}async cocAction(e,...t){let i=this.actions.get(e);if(!i)throw new Error(`Action "${e}" not exists`);return await Promise.resolve(i.apply(null,t))}getHandler(){return this.handler}dispose(){this.removeAllListeners(),ge.dispose(),Kt.dispose(),b.dispose(),C.dispose(),Ze.dispose(),Vt.stopAll(),Vt.dispose(),this.handler&&this.handler.dispose(),Ft.dispose(),me.dispose(),cs.dispose(),St.dispose()}},xJ=OP;var lSe=CJ().default;lSe({reader:process.stdin,writer:process.stdout});process.on("uncaughtException",function(r){let e="Uncaught exception: "+r.message;console.error(e),LP.error("uncaughtException",r.stack)});process.on("unhandledRejection",function(r,e){r instanceof Error?console.error("UnhandledRejection: "+r.message+` +`+r.stack):console.error("UnhandledRejection: "+r),LP.error("unhandledRejection ",e,r)}); /*! * @description Recursive object extending * @author Viacheslav Lotsmanov @@ -47061,44366 +272,53 @@ module.exports = function (str, opts) { * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - - - -function isSpecificValue(val) { - return ( - val instanceof Buffer - || val instanceof Date - || val instanceof RegExp - ) ? true : false; -} - -function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = Buffer.alloc - ? Buffer.alloc(val.length) - : new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error('Unexpected situation'); - } -} - -/** - * Recursive cloning array. +/*! + * ISC License + * + * Copyright (c) 2018, Andrea Giammarchi, @WebReflection + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE + * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. */ -function deepCloneArray(arr) { - var clone = []; - arr.forEach(function (item, index) { - if (typeof item === 'object' && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; -} - -function safeGetProperty(object, property) { - return property === '__proto__' ? undefined : object[property]; -} - -/** - * Extening object that entered in first argument. - * - * Returns extended object or false if have no target object or incorrect type. - * - * If you wish to clone source object (without modify it), just use empty new - * object as first argument, like this: - * deepExtend({}, yourObj_1, [yourObj_N]); +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed */ -var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } - - if (arguments.length < 2) { - return arguments[0]; - } - - var target = arguments[0]; - - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - - var val, src, clone; - - args.forEach(function (obj) { - // skip argument if isn't an object, is null, or is an array - if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { - return; - } - - Object.keys(obj).forEach(function (key) { - src = safeGetProperty(target, key); // source value - val = safeGetProperty(obj, key); // new value - - // recursion prevention - if (val === target) { - return; - - /** - * if new value isn't object then just overwrite by new value - * instead of extending. - */ - } else if (typeof val !== 'object' || val === null) { - target[key] = val; - return; - - // just clone arrays (and recursive clone objects inside) - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; - - // custom cloning and overwrite for specific objects - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; - - // overwrite by new value if source isn't object or array - } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; - - // source value and new value is objects both, extending... - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); - - return target; -}; - - -/***/ }), -/* 357 */ -/***/ (function(module, exports) { - -module.exports = function (args, opts) { - if (!opts) opts = {}; - - var flags = { bools : {}, strings : {}, unknownFn: null }; - - if (typeof opts['unknown'] === 'function') { - flags.unknownFn = opts['unknown']; - } - - if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { - flags.allBools = true; - } else { - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - } - - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function (key) { - aliases[key] = [].concat(opts.alias[key]); - aliases[key].forEach(function (x) { - aliases[x] = [key].concat(aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - if (aliases[key]) { - flags.strings[aliases[key]] = true; - } - }); - - var defaults = opts['default'] || {}; - - var argv = { _ : [] }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - var notFlags = []; - - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--')+1); - args = args.slice(0, args.indexOf('--')); - } - - function argDefined(key, arg) { - return (flags.allBools && /^--[^=]+$/.test(arg)) || - flags.strings[key] || flags.bools[key] || aliases[key]; - } - - function setArg (key, val, arg) { - if (arg && flags.unknownFn && !argDefined(key, arg)) { - if (flags.unknownFn(arg) === false) return; - } - - var value = !flags.strings[key] && isNumber(val) - ? Number(val) : val - ; - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), value); - }); - } - - function setKey (obj, keys, value) { - var o = obj; - for (var i = 0; i < keys.length-1; i++) { - var key = keys[i]; - if (key === '__proto__') return; - if (o[key] === undefined) o[key] = {}; - if (o[key] === Object.prototype || o[key] === Number.prototype - || o[key] === String.prototype) o[key] = {}; - if (o[key] === Array.prototype) o[key] = []; - o = o[key]; - } - - var key = keys[keys.length - 1]; - if (key === '__proto__') return; - if (o === Object.prototype || o === Number.prototype - || o === String.prototype) o = {}; - if (o === Array.prototype) o = []; - if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } - } - - function aliasIsBoolean(key) { - return aliases[key].some(function (x) { - return flags.bools[x]; - }); - } - - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - var key = m[1]; - var value = m[2]; - if (flags.bools[key]) { - value = value !== 'false'; - } - setArg(key, value, arg); - } - else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } - else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !/^-/.test(next) - && !flags.bools[key] - && !flags.allBools - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, next, arg); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j+2); - - if (next === '-') { - setArg(letters[j], next, arg) - continue; - } - - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split('=')[1], arg); - broken = true; - break; - } - - if (/[A-Za-z]/.test(letters[j]) - && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next, arg); - broken = true; - break; - } - - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2), arg); - broken = true; - break; - } - else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); - } - } - - var key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) - && !flags.bools[key] - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, args[i+1], arg); - i++; - } - else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { - setArg(key, args[i+1] === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - } - else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); - } - if (opts.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - - Object.keys(defaults).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) { - setKey(argv, key.split('.'), defaults[key]); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), defaults[key]); - }); - } - }); - - if (opts['--']) { - argv['--'] = new Array(); - notFlags.forEach(function(key) { - argv['--'].push(key); - }); - } - else { - notFlags.forEach(function(key) { - argv._.push(key); - }); - } - - return argv; -}; - -function hasKey (obj, keys) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - o = (o[key] || {}); - }); - - var key = keys[keys.length - 1]; - return key in o; -} - -function isNumber (x) { - if (typeof x === 'number') return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} - - - -/***/ }), -/* 358 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(65); -const follow_redirects_1 = __webpack_require__(359); -const uuid_1 = __webpack_require__(259); -const fs_1 = tslib_1.__importDefault(__webpack_require__(66)); -const mkdirp_1 = tslib_1.__importDefault(__webpack_require__(272)); -const path_1 = tslib_1.__importDefault(__webpack_require__(82)); -const tar_1 = tslib_1.__importDefault(__webpack_require__(364)); -const unzipper_1 = tslib_1.__importDefault(__webpack_require__(394)); -const fetch_1 = __webpack_require__(487); -const content_disposition_1 = tslib_1.__importDefault(__webpack_require__(498)); -const logger = __webpack_require__(64)('model-download'); -/** - * Download file from url, with optional untar/unzip support. - * - * @param {string} url - * @param {DownloadOptions} options contains dest folder and optional onProgress callback - */ -function download(url, options, token) { - let { dest, onProgress, extract } = options; - if (!dest || !path_1.default.isAbsolute(dest)) { - throw new Error(`Expect absolute file path for dest option.`); - } - let stat; - try { - stat = fs_1.default.statSync(dest); - } - catch (_e) { - mkdirp_1.default.sync(dest); - } - if (stat && !stat.isDirectory()) { - throw new Error(`${dest} exists, but not directory!`); - } - let mod = url.startsWith('https') ? follow_redirects_1.https : follow_redirects_1.http; - let opts = fetch_1.resolveRequestOptions(url, options); - let extname = path_1.default.extname(url); - return new Promise((resolve, reject) => { - if (token) { - let disposable = token.onCancellationRequested(() => { - disposable.dispose(); - req.destroy(new Error('request aborted')); - }); - } - const req = mod.request(opts, (res) => { - var _a; - if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) { - let headers = res.headers || {}; - let dispositionHeader = headers['content-disposition']; - if (!extname && dispositionHeader) { - let disposition = content_disposition_1.default.parse(dispositionHeader); - if ((_a = disposition.parameters) === null || _a === void 0 ? void 0 : _a.filename) { - extname = path_1.default.extname(disposition.parameters.filename); - } - } - if (extract === true) { - if (extname === '.zip' || headers['content-type'] == 'application/zip') { - extract = 'unzip'; - } - else if (extname == '.tgz') { - extract = 'untar'; - } - else { - reject(new Error(`Unable to extract for ${url}`)); - return; - } - } - let total = Number(headers['content-length']); - let cur = 0; - if (!isNaN(total)) { - res.on('data', chunk => { - cur += chunk.length; - let percent = (cur / total * 100).toFixed(1); - if (onProgress) { - onProgress(percent); - } - else { - logger.info(`Download ${url} progress ${percent}%`); - } - }); - } - res.on('error', err => { - reject(new Error(`Unable to connect ${url}: ${err.message}`)); - }); - res.on('end', () => { - logger.info('Download completed:', url); - }); - let stream; - if (extract === 'untar') { - stream = res.pipe(tar_1.default.x({ strip: 1, C: dest })); - } - else if (extract === 'unzip') { - stream = res.pipe(unzipper_1.default.Extract({ path: dest })); - } - else { - dest = path_1.default.join(dest, `${uuid_1.v1()}${extname}`); - stream = res.pipe(fs_1.default.createWriteStream(dest)); - } - stream.on('finish', () => { - logger.info(`Downloaded ${url} => ${dest}`); - setTimeout(() => { - resolve(dest); - }, 100); - }); - stream.on('error', reject); - } - else { - reject(new Error(`Invalid response from ${url}: ${res.statusCode}`)); - } - }); - req.on('error', reject); - req.on('timeout', () => { - req.destroy(new Error(`request timeout after ${options.timeout}ms`)); - }); - if (options.timeout) { - req.setTimeout(options.timeout); - } - req.end(); - }); -} -exports.default = download; -//# sourceMappingURL=download.js.map - -/***/ }), -/* 359 */ -/***/ (function(module, exports, __webpack_require__) { - -var url = __webpack_require__(360); -var URL = url.URL; -var http = __webpack_require__(361); -var https = __webpack_require__(362); -var Writable = __webpack_require__(106).Writable; -var assert = __webpack_require__(108); -var debug = __webpack_require__(363); - -// Create handlers that pass events from native requests -var eventHandlers = Object.create(null); -["abort", "aborted", "connect", "error", "socket", "timeout"].forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - if (callback) { - this.once("timeout", callback); - } - - if (this.socket) { - startTimer(this, msecs); - } - else { - var self = this; - this._currentRequest.once("socket", function () { - startTimer(self, msecs); - }); - } - - this.once("response", clearTimer); - this.once("error", clearTimer); - - return this; -}; - -function startTimer(request, msecs) { - clearTimeout(request._timeout); - request._timeout = setTimeout(function () { - request.emit("timeout"); - }, msecs); -} - -function clearTimer() { - clearTimeout(this._timeout); -} - -// Proxy all other public ClientRequest methods -[ - "abort", "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url.format(this._options); - - // Set up event handlers - request._redirectable = this; - for (var event in eventHandlers) { - /* istanbul ignore else */ - if (event) { - request.on(event, eventHandlers[event]); - } - } - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end. - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - var location = response.headers.location; - if (location && this._options.followRedirects !== false && - statusCode >= 300 && statusCode < 400) { - // Abort the current request - this._currentRequest.removeAllListeners(); - this._currentRequest.on("error", noop); - this._currentRequest.abort(); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || - url.parse(this._currentUrl).hostname; - - // Create the redirected request - var redirectUrl = url.resolve(this._currentUrl, location); - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); - - // Drop the Authorization header if redirecting to another host - if (redirectUrlParts.hostname !== previousHostName) { - removeMatchingHeaders(/^authorization$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (typeof this._options.beforeRedirect === "function") { - var responseDetails = { headers: response.headers }; - try { - this._options.beforeRedirect.call(null, this._options, responseDetails); - } - catch (err) { - this.emit("error", err); - return; - } - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - try { - this._performRequest(); - } - catch (cause) { - var error = new RedirectionError("Redirected request failed: " + cause.message); - error.cause = cause; - this.emit("error", error); - } - } - else { - // The response is not a redirect; return it as-is - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - } -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - wrappedProtocol.request = function (input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url.parse(urlStr); - } - } - else if (URL && (input instanceof URL)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - }; - - // Executes a GET request, following redirects - wrappedProtocol.get = function (input, options, callback) { - var request = wrappedProtocol.request(input, options, callback); - request.end(); - return request; - }; - }); - return exports; -} - -/* istanbul ignore next */ -function noop() { /* empty */ } - -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return lastValue; -} - -function createErrorType(code, defaultMessage) { - function CustomError(message) { - Error.captureStackTrace(this, this.constructor); - this.message = message || defaultMessage; - } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} - -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; - - -/***/ }), -/* 360 */ -/***/ (function(module, exports) { - -module.exports = require("url"); - -/***/ }), -/* 361 */ -/***/ (function(module, exports) { - -module.exports = require("http"); - -/***/ }), -/* 362 */ -/***/ (function(module, exports) { - -module.exports = require("https"); - -/***/ }), -/* 363 */ -/***/ (function(module, exports, __webpack_require__) { - -var debug; -try { - /* eslint global-require: off */ - debug = __webpack_require__(68)("follow-redirects"); -} -catch (error) { - debug = function () { /* */ }; -} -module.exports = debug; - - -/***/ }), -/* 364 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// high-level commands -exports.c = exports.create = __webpack_require__(365) -exports.r = exports.replace = __webpack_require__(386) -exports.t = exports.list = __webpack_require__(384) -exports.u = exports.update = __webpack_require__(387) -exports.x = exports.extract = __webpack_require__(388) - -// classes -exports.Pack = __webpack_require__(367) -exports.Unpack = __webpack_require__(389) -exports.Parse = __webpack_require__(385) -exports.ReadEntry = __webpack_require__(374) -exports.WriteEntry = __webpack_require__(376) -exports.Header = __webpack_require__(378) -exports.Pax = __webpack_require__(377) -exports.types = __webpack_require__(375) - - -/***/ }), -/* 365 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// tar -c -const hlo = __webpack_require__(366) - -const Pack = __webpack_require__(367) -const fs = __webpack_require__(66) -const fsm = __webpack_require__(383) -const t = __webpack_require__(384) -const path = __webpack_require__(82) - -const c = module.exports = (opt_, files, cb) => { - if (typeof files === 'function') - cb = files - - if (Array.isArray(opt_)) - files = opt_, opt_ = {} - - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') - - files = Array.from(files) - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') - - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') - - return opt.file && opt.sync ? createFileSync(opt, files) - : opt.file ? createFile(opt, files, cb) - : opt.sync ? createSync(opt, files) - : create(opt, files) -} - -const createFileSync = (opt, files) => { - const p = new Pack.Sync(opt) - const stream = new fsm.WriteStreamSync(opt.file, { - mode: opt.mode || 0o666 - }) - p.pipe(stream) - addFilesSync(p, files) -} - -const createFile = (opt, files, cb) => { - const p = new Pack(opt) - const stream = new fsm.WriteStream(opt.file, { - mode: opt.mode || 0o666 - }) - p.pipe(stream) - - const promise = new Promise((res, rej) => { - stream.on('error', rej) - stream.on('close', res) - p.on('error', rej) - }) - - addFilesAsync(p, files) - - return cb ? promise.then(cb, cb) : promise -} - -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') - t({ - file: path.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry) - }) - else - p.add(file) - }) - p.end() -} - -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') - return t({ - file: path.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: entry => p.add(entry) - }).then(_ => addFilesAsync(p, files)) - else - p.add(file) - } - p.end() -} - -const createSync = (opt, files) => { - const p = new Pack.Sync(opt) - addFilesSync(p, files) - return p -} - -const create = (opt, files) => { - const p = new Pack(opt) - addFilesAsync(p, files) - return p -} - - -/***/ }), -/* 366 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// turn tar(1) style args like `C` into the more verbose things like `cwd` - -const argmap = new Map([ - ['C', 'cwd'], - ['f', 'file'], - ['z', 'gzip'], - ['P', 'preservePaths'], - ['U', 'unlink'], - ['strip-components', 'strip'], - ['stripComponents', 'strip'], - ['keep-newer', 'newer'], - ['keepNewer', 'newer'], - ['keep-newer-files', 'newer'], - ['keepNewerFiles', 'newer'], - ['k', 'keep'], - ['keep-existing', 'keep'], - ['keepExisting', 'keep'], - ['m', 'noMtime'], - ['no-mtime', 'noMtime'], - ['p', 'preserveOwner'], - ['L', 'follow'], - ['h', 'follow'] -]) - -const parse = module.exports = opt => opt ? Object.keys(opt).map(k => [ - argmap.has(k) ? argmap.get(k) : k, opt[k] -]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} - - -/***/ }), -/* 367 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// A readable tar stream creator -// Technically, this is a transform stream that you write paths into, -// and tar format comes out of. -// The `add()` method is like `write()` but returns this, -// and end() return `this` as well, so you can -// do `new Pack(opt).add('files').add('dir').end().pipe(output) -// You could also do something like: -// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) - -class PackJob { - constructor (path, absolute) { - this.path = path || './' - this.absolute = absolute - this.entry = null - this.stat = null - this.readdir = null - this.pending = false - this.ignore = false - this.piped = false - } -} - -const MiniPass = __webpack_require__(368) -const zlib = __webpack_require__(372) -const ReadEntry = __webpack_require__(374) -const WriteEntry = __webpack_require__(376) -const WriteEntrySync = WriteEntry.Sync -const WriteEntryTar = WriteEntry.Tar -const Yallist = __webpack_require__(369) -const EOF = Buffer.alloc(1024) -const ONSTAT = Symbol('onStat') -const ENDED = Symbol('ended') -const QUEUE = Symbol('queue') -const CURRENT = Symbol('current') -const PROCESS = Symbol('process') -const PROCESSING = Symbol('processing') -const PROCESSJOB = Symbol('processJob') -const JOBS = Symbol('jobs') -const JOBDONE = Symbol('jobDone') -const ADDFSENTRY = Symbol('addFSEntry') -const ADDTARENTRY = Symbol('addTarEntry') -const STAT = Symbol('stat') -const READDIR = Symbol('readdir') -const ONREADDIR = Symbol('onreaddir') -const PIPE = Symbol('pipe') -const ENTRY = Symbol('entry') -const ENTRYOPT = Symbol('entryOpt') -const WRITEENTRYCLASS = Symbol('writeEntryClass') -const WRITE = Symbol('write') -const ONDRAIN = Symbol('ondrain') - -const fs = __webpack_require__(66) -const path = __webpack_require__(82) -const warner = __webpack_require__(380) - -const Pack = warner(class Pack extends MiniPass { - constructor (opt) { - super(opt) - opt = opt || Object.create(null) - this.opt = opt - this.file = opt.file || '' - this.cwd = opt.cwd || process.cwd() - this.maxReadSize = opt.maxReadSize - this.preservePaths = !!opt.preservePaths - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '') - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.readdirCache = opt.readdirCache || new Map() - - this[WRITEENTRYCLASS] = WriteEntry - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - - this.portable = !!opt.portable - this.zip = null - if (opt.gzip) { - if (typeof opt.gzip !== 'object') - opt.gzip = {} - if (this.portable) - opt.gzip.portable = true - this.zip = new zlib.Gzip(opt.gzip) - this.zip.on('data', chunk => super.write(chunk)) - this.zip.on('end', _ => super.end()) - this.zip.on('drain', _ => this[ONDRAIN]()) - this.on('resume', _ => this.zip.resume()) - } else - this.on('drain', this[ONDRAIN]) - - this.noDirRecurse = !!opt.noDirRecurse - this.follow = !!opt.follow - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null - - this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true - - this[QUEUE] = new Yallist - this[JOBS] = 0 - this.jobs = +opt.jobs || 4 - this[PROCESSING] = false - this[ENDED] = false - } - - [WRITE] (chunk) { - return super.write(chunk) - } - - add (path) { - this.write(path) - return this - } - - end (path) { - if (path) - this.write(path) - this[ENDED] = true - this[PROCESS]() - return this - } - - write (path) { - if (this[ENDED]) - throw new Error('write after end') - - if (path instanceof ReadEntry) - this[ADDTARENTRY](path) - else - this[ADDFSENTRY](path) - return this.flowing - } - - [ADDTARENTRY] (p) { - const absolute = path.resolve(this.cwd, p.path) - if (this.prefix) - p.path = this.prefix + '/' + p.path.replace(/^\.(\/+|$)/, '') - - // in this case, we don't have to wait for the stat - if (!this.filter(p.path, p)) - p.resume() - else { - const job = new PackJob(p.path, absolute, false) - job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) - job.entry.on('end', _ => this[JOBDONE](job)) - this[JOBS] += 1 - this[QUEUE].push(job) - } - - this[PROCESS]() - } - - [ADDFSENTRY] (p) { - const absolute = path.resolve(this.cwd, p) - if (this.prefix) - p = this.prefix + '/' + p.replace(/^\.(\/+|$)/, '') - - this[QUEUE].push(new PackJob(p, absolute)) - this[PROCESS]() - } - - [STAT] (job) { - job.pending = true - this[JOBS] += 1 - const stat = this.follow ? 'stat' : 'lstat' - fs[stat](job.absolute, (er, stat) => { - job.pending = false - this[JOBS] -= 1 - if (er) - this.emit('error', er) - else - this[ONSTAT](job, stat) - }) - } - - [ONSTAT] (job, stat) { - this.statCache.set(job.absolute, stat) - job.stat = stat - - // now we have the stat, we can filter it. - if (!this.filter(job.path, stat)) - job.ignore = true - - this[PROCESS]() - } - - [READDIR] (job) { - job.pending = true - this[JOBS] += 1 - fs.readdir(job.absolute, (er, entries) => { - job.pending = false - this[JOBS] -= 1 - if (er) - return this.emit('error', er) - this[ONREADDIR](job, entries) - }) - } - - [ONREADDIR] (job, entries) { - this.readdirCache.set(job.absolute, entries) - job.readdir = entries - this[PROCESS]() - } - - [PROCESS] () { - if (this[PROCESSING]) - return - - this[PROCESSING] = true - for (let w = this[QUEUE].head; - w !== null && this[JOBS] < this.jobs; - w = w.next) { - this[PROCESSJOB](w.value) - if (w.value.ignore) { - const p = w.next - this[QUEUE].removeNode(w) - w.next = p - } - } - - this[PROCESSING] = false - - if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { - if (this.zip) - this.zip.end(EOF) - else { - super.write(EOF) - super.end() - } - } - } - - get [CURRENT] () { - return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value - } - - [JOBDONE] (job) { - this[QUEUE].shift() - this[JOBS] -= 1 - this[PROCESS]() - } - - [PROCESSJOB] (job) { - if (job.pending) - return - - if (job.entry) { - if (job === this[CURRENT] && !job.piped) - this[PIPE](job) - return - } - - if (!job.stat) { - if (this.statCache.has(job.absolute)) - this[ONSTAT](job, this.statCache.get(job.absolute)) - else - this[STAT](job) - } - if (!job.stat) - return - - // filtered out! - if (job.ignore) - return - - if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { - if (this.readdirCache.has(job.absolute)) - this[ONREADDIR](job, this.readdirCache.get(job.absolute)) - else - this[READDIR](job) - if (!job.readdir) - return - } - - // we know it doesn't have an entry, because that got checked above - job.entry = this[ENTRY](job) - if (!job.entry) { - job.ignore = true - return - } - - if (job === this[CURRENT] && !job.piped) - this[PIPE](job) - } - - [ENTRYOPT] (job) { - return { - onwarn: (code, msg, data) => this.warn(code, msg, data), - noPax: this.noPax, - cwd: this.cwd, - absolute: job.absolute, - preservePaths: this.preservePaths, - maxReadSize: this.maxReadSize, - strict: this.strict, - portable: this.portable, - linkCache: this.linkCache, - statCache: this.statCache, - noMtime: this.noMtime, - mtime: this.mtime - } - } - - [ENTRY] (job) { - this[JOBS] += 1 - try { - return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) - .on('end', () => this[JOBDONE](job)) - .on('error', er => this.emit('error', er)) - } catch (er) { - this.emit('error', er) - } - } - - [ONDRAIN] () { - if (this[CURRENT] && this[CURRENT].entry) - this[CURRENT].entry.resume() - } - - // like .pipe() but using super, because our write() is special - [PIPE] (job) { - job.piped = true - - if (job.readdir) - job.readdir.forEach(entry => { - const p = this.prefix ? - job.path.slice(this.prefix.length + 1) || './' - : job.path - - const base = p === './' ? '' : p.replace(/\/*$/, '/') - this[ADDFSENTRY](base + entry) - }) - - const source = job.entry - const zip = this.zip - - if (zip) - source.on('data', chunk => { - if (!zip.write(chunk)) - source.pause() - }) - else - source.on('data', chunk => { - if (!super.write(chunk)) - source.pause() - }) - } - - pause () { - if (this.zip) - this.zip.pause() - return super.pause() - } -}) - -class PackSync extends Pack { - constructor (opt) { - super(opt) - this[WRITEENTRYCLASS] = WriteEntrySync - } - - // pause/resume are no-ops in sync streams. - pause () {} - resume () {} - - [STAT] (job) { - const stat = this.follow ? 'statSync' : 'lstatSync' - this[ONSTAT](job, fs[stat](job.absolute)) - } - - [READDIR] (job, stat) { - this[ONREADDIR](job, fs.readdirSync(job.absolute)) - } - - // gotta get it all in this tick - [PIPE] (job) { - const source = job.entry - const zip = this.zip - - if (job.readdir) - job.readdir.forEach(entry => { - const p = this.prefix ? - job.path.slice(this.prefix.length + 1) || './' - : job.path - - const base = p === './' ? '' : p.replace(/\/*$/, '/') - this[ADDFSENTRY](base + entry) - }) - - if (zip) - source.on('data', chunk => { - zip.write(chunk) - }) - else - source.on('data', chunk => { - super[WRITE](chunk) - }) - } -} - -Pack.Sync = PackSync - -module.exports = Pack - - -/***/ }), -/* 368 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const EE = __webpack_require__(198) -const Stream = __webpack_require__(106) -const Yallist = __webpack_require__(369) -const SD = __webpack_require__(371).StringDecoder - -const EOF = Symbol('EOF') -const MAYBE_EMIT_END = Symbol('maybeEmitEnd') -const EMITTED_END = Symbol('emittedEnd') -const EMITTING_END = Symbol('emittingEnd') -const CLOSED = Symbol('closed') -const READ = Symbol('read') -const FLUSH = Symbol('flush') -const FLUSHCHUNK = Symbol('flushChunk') -const ENCODING = Symbol('encoding') -const DECODER = Symbol('decoder') -const FLOWING = Symbol('flowing') -const PAUSED = Symbol('paused') -const RESUME = Symbol('resume') -const BUFFERLENGTH = Symbol('bufferLength') -const BUFFERPUSH = Symbol('bufferPush') -const BUFFERSHIFT = Symbol('bufferShift') -const OBJECTMODE = Symbol('objectMode') -const DESTROYED = Symbol('destroyed') - -// TODO remove when Node v8 support drops -const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' -const ASYNCITERATOR = doIter && Symbol.asyncIterator - || Symbol('asyncIterator not implemented') -const ITERATOR = doIter && Symbol.iterator - || Symbol('iterator not implemented') - -// events that mean 'the stream is over' -// these are treated specially, and re-emitted -// if they are listened for after emitting. -const isEndish = ev => - ev === 'end' || - ev === 'finish' || - ev === 'prefinish' - -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 - -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) - -module.exports = class Minipass extends Stream { - constructor (options) { - super() - this[FLOWING] = false - // whether we're explicitly paused - this[PAUSED] = false - this.pipes = new Yallist() - this.buffer = new Yallist() - this[OBJECTMODE] = options && options.objectMode || false - if (this[OBJECTMODE]) - this[ENCODING] = null - else - this[ENCODING] = options && options.encoding || null - if (this[ENCODING] === 'buffer') - this[ENCODING] = null - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null - this[EOF] = false - this[EMITTED_END] = false - this[EMITTING_END] = false - this[CLOSED] = false - this.writable = true - this.readable = true - this[BUFFERLENGTH] = 0 - this[DESTROYED] = false - } - - get bufferLength () { return this[BUFFERLENGTH] } - - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') - - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') - - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null - if (this.buffer.length) - this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) - } - - this[ENCODING] = enc - } - - setEncoding (enc) { - this.encoding = enc - } - - get objectMode () { return this[OBJECTMODE] } - set objectMode (ॐ ) { this[OBJECTMODE] = this[OBJECTMODE] || !!ॐ } - - write (chunk, encoding, cb) { - if (this[EOF]) - throw new Error('write after end') - - if (this[DESTROYED]) { - this.emit('error', Object.assign( - new Error('Cannot call write after a stream was destroyed'), - { code: 'ERR_STREAM_DESTROYED' } - )) - return true - } - - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - - if (!encoding) - encoding = 'utf8' - - // convert array buffers and typed array views into buffers - // at some point in the future, we may want to do the opposite! - // leave strings and buffers as-is - // anything else switches us into object mode - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk) - else if (typeof chunk !== 'string') - // use the setter so we throw if we have encoding set - this.objectMode = true - } - - // this ensures at this point that the chunk is a buffer or string - // don't buffer it up or send it to the decoder - if (!this.objectMode && !chunk.length) { - const ret = this.flowing - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - cb() - return ret - } - - // fast-path writing strings of same encoding to a stream with - // an empty buffer, skipping the buffer/decoder dance - if (typeof chunk === 'string' && !this[OBJECTMODE] && - // unless it is a string already ready for us to use - !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding) - } - - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) - - try { - return this.flowing - ? (this.emit('data', chunk), this.flowing) - : (this[BUFFERPUSH](chunk), false) - } finally { - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - cb() - } - } - - read (n) { - if (this[DESTROYED]) - return null - - try { - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) - return null - - if (this[OBJECTMODE]) - n = null - - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = new Yallist([ - Array.from(this.buffer).join('') - ]) - else - this.buffer = new Yallist([ - Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) - ]) - } - - return this[READ](n || null, this.buffer.head.value) - } finally { - this[MAYBE_EMIT_END]() - } - } - - [READ] (n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT]() - else { - this.buffer.head.value = chunk.slice(n) - chunk = chunk.slice(0, n) - this[BUFFERLENGTH] -= n - } - - this.emit('data', chunk) - - if (!this.buffer.length && !this[EOF]) - this.emit('drain') - - return chunk - } - - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - if (cb) - this.once('end', cb) - this[EOF] = true - this.writable = false - - // if we haven't written anything, then go ahead and emit, - // even if we're not reading. - // we'll re-emit if a new 'end' listener is added anyway. - // This makes MP more suitable to write-only use cases. - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END]() - return this - } - - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return - - this[PAUSED] = false - this[FLOWING] = true - this.emit('resume') - if (this.buffer.length) - this[FLUSH]() - else if (this[EOF]) - this[MAYBE_EMIT_END]() - else - this.emit('drain') - } - - resume () { - return this[RESUME]() - } - - pause () { - this[FLOWING] = false - this[PAUSED] = true - } - - get destroyed () { - return this[DESTROYED] - } - - get flowing () { - return this[FLOWING] - } - - get paused () { - return this[PAUSED] - } - - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - return this.buffer.push(chunk) - } - - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer.head.value.length - } - return this.buffer.shift() - } - - [FLUSH] () { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) - - if (!this.buffer.length && !this[EOF]) - this.emit('drain') - } - - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } - - pipe (dest, opts) { - if (this[DESTROYED]) - return - - const ended = this[EMITTED_END] - opts = opts || {} - if (dest === process.stdout || dest === process.stderr) - opts.end = false - else - opts.end = opts.end !== false - - const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() } - this.pipes.push(p) - - dest.on('drain', p.ondrain) - this[RESUME]() - // piping an ended stream ends immediately - if (ended && p.opts.end) - p.dest.end() - return dest - } - - addListener (ev, fn) { - return this.on(ev, fn) - } - - on (ev, fn) { - try { - return super.on(ev, fn) - } finally { - if (ev === 'data' && !this.pipes.length && !this.flowing) - this[RESUME]() - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev) - this.removeAllListeners(ev) - } - } - } - - get emittedEnd () { - return this[EMITTED_END] - } - - [MAYBE_EMIT_END] () { - if (!this[EMITTING_END] && - !this[EMITTED_END] && - !this[DESTROYED] && - this.buffer.length === 0 && - this[EOF]) { - this[EMITTING_END] = true - this.emit('end') - this.emit('prefinish') - this.emit('finish') - if (this[CLOSED]) - this.emit('close') - this[EMITTING_END] = false - } - } - - emit (ev, data) { - // error and close are only events allowed after calling destroy() - if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) - return - else if (ev === 'data') { - if (!data) - return - - if (this.pipes.length) - this.pipes.forEach(p => - p.dest.write(data) === false && this.pause()) - } else if (ev === 'end') { - // only actual end gets this treatment - if (this[EMITTED_END] === true) - return - - this[EMITTED_END] = true - this.readable = false - - if (this[DECODER]) { - data = this[DECODER].end() - if (data) { - this.pipes.forEach(p => p.dest.write(data)) - super.emit('data', data) - } - } - - this.pipes.forEach(p => { - p.dest.removeListener('drain', p.ondrain) - if (p.opts.end) - p.dest.end() - }) - } else if (ev === 'close') { - this[CLOSED] = true - // don't emit close before 'end' and 'finish' - if (!this[EMITTED_END] && !this[DESTROYED]) - return - } - - // TODO: replace with a spread operator when Node v4 support drops - const args = new Array(arguments.length) - args[0] = ev - args[1] = data - if (arguments.length > 2) { - for (let i = 2; i < arguments.length; i++) { - args[i] = arguments[i] - } - } - - try { - return super.emit.apply(this, args) - } finally { - if (!isEndish(ev)) - this[MAYBE_EMIT_END]() - else - this.removeAllListeners(ev) - } - } - - // const all = await stream.collect() - collect () { - const buf = [] - if (!this[OBJECTMODE]) - buf.dataLength = 0 - // set the promise first, in case an error is raised - // by triggering the flow here. - const p = this.promise() - this.on('data', c => { - buf.push(c) - if (!this[OBJECTMODE]) - buf.dataLength += c.length - }) - return p.then(() => buf) - } - - // const data = await stream.concat() - concat () { - return this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this.collect().then(buf => - this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) - } - - // stream.promise().then(() => done, er => emitted error) - promise () { - return new Promise((resolve, reject) => { - this.on(DESTROYED, () => reject(new Error('stream destroyed'))) - this.on('end', () => resolve()) - this.on('error', er => reject(er)) - }) - } - - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) - - if (this[EOF]) - return Promise.resolve({ done: true }) - - let resolve = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - resolve({ done: true }) - } - const ondestroy = () => onerr(new Error('stream destroyed')) - return new Promise((res, rej) => { - reject = rej - resolve = res - this.once(DESTROYED, ondestroy) - this.once('error', onerr) - this.once('end', onend) - this.once('data', ondata) - }) - } - - return { next } - } - - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } - } - return { next } - } - - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this - } - - this[DESTROYED] = true - - // throw away all buffered data, it's never coming out - this.buffer = new Yallist() - this[BUFFERLENGTH] = 0 - - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() - - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) - - return this - } - - static isStream (s) { - return !!s && (s instanceof Minipass || s instanceof Stream || - s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable - )) - } -} - - -/***/ }), -/* 369 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = Yallist - -Yallist.Node = Node -Yallist.create = Yallist - -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } - - self.tail = null - self.head = null - self.length = 0 - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) - } - } - - return self -} - -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next - var prev = node.prev - - if (next) { - next.prev = prev - } - - if (prev) { - prev.next = next - } - - if (node === this.head) { - this.head = next - } - if (node === this.tail) { - this.tail = prev - } - - node.list.length-- - node.next = null - node.prev = null - node.list = null - - return next -} - -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node - } - - this.head = node - if (!this.tail) { - this.tail = node - } - this.length++ -} - -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node - } - - this.tail = node - if (!this.head) { - this.head = node - } - this.length++ -} - -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null - } - this.length-- - return res -} - -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null - } else { - this.tail = null - } - this.length-- - return res -} - -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next - } -} - -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev - } -} - -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next - } - return res -} - -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev - } - return res -} - -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next - } - - return acc -} - -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev - } - - return acc -} - -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next - } - return arr -} - -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev - } - return arr -} - -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1 - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next - } - - var ret = [] - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value) - walker = this.removeNode(walker) - } - if (walker === null) { - walker = this.tail - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]) - } - return ret; -} - -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p - } - this.head = tail - this.tail = head - return this -} - -function insert (self, node, value) { - var inserted = node === self.head ? - new Node(value, null, node, self) : - new Node(value, node, node.next, self) - - if (inserted.next === null) { - self.tail = inserted - } - if (inserted.prev === null) { - self.head = inserted - } - - self.length++ - - return inserted -} - -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail - } - self.length++ -} - -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ -} - -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } - - this.list = list - this.value = value - - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null - } - - if (next) { - next.prev = this - this.next = next - } else { - this.next = null - } -} - -try { - // add if support for Symbol.iterator is present - __webpack_require__(370)(Yallist) -} catch (er) {} - - -/***/ }), -/* 370 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = function (Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value - } - } -} - - -/***/ }), -/* 371 */ -/***/ (function(module, exports) { - -module.exports = require("string_decoder"); - -/***/ }), -/* 372 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const assert = __webpack_require__(108) -const Buffer = __webpack_require__(310).Buffer -const realZlib = __webpack_require__(145) - -const constants = exports.constants = __webpack_require__(373) -const Minipass = __webpack_require__(368) - -const OriginalBufferConcat = Buffer.concat - -const _superWrite = Symbol('_superWrite') -class ZlibError extends Error { - constructor (err) { - super('zlib: ' + err.message) - this.code = err.code - this.errno = err.errno - /* istanbul ignore if */ - if (!this.code) - this.code = 'ZLIB_ERROR' - - this.message = 'zlib: ' + err.message - Error.captureStackTrace(this, this.constructor) - } - - get name () { - return 'ZlibError' - } -} - -// the Zlib class they all inherit from -// This thing manages the queue of requests, and returns -// true or false if there is anything in the queue when -// you call the .write() method. -const _opts = Symbol('opts') -const _flushFlag = Symbol('flushFlag') -const _finishFlushFlag = Symbol('finishFlushFlag') -const _fullFlushFlag = Symbol('fullFlushFlag') -const _handle = Symbol('handle') -const _onError = Symbol('onError') -const _sawError = Symbol('sawError') -const _level = Symbol('level') -const _strategy = Symbol('strategy') -const _ended = Symbol('ended') -const _defaultFullFlush = Symbol('_defaultFullFlush') - -class ZlibBase extends Minipass { - constructor (opts, mode) { - if (!opts || typeof opts !== 'object') - throw new TypeError('invalid options for ZlibBase constructor') - - super(opts) - this[_sawError] = false - this[_ended] = false - this[_opts] = opts - - this[_flushFlag] = opts.flush - this[_finishFlushFlag] = opts.finishFlush - // this will throw if any options are invalid for the class selected - try { - this[_handle] = new realZlib[mode](opts) - } catch (er) { - // make sure that all errors get decorated properly - throw new ZlibError(er) - } - - this[_onError] = (err) => { - // no sense raising multiple errors, since we abort on the first one. - if (this[_sawError]) - return - - this[_sawError] = true - - // there is no way to cleanly recover. - // continuing only obscures problems. - this.close() - this.emit('error', err) - } - - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - this.once('end', () => this.close) - } - - close () { - if (this[_handle]) { - this[_handle].close() - this[_handle] = null - this.emit('close') - } - } - - reset () { - if (!this[_sawError]) { - assert(this[_handle], 'zlib binding closed') - return this[_handle].reset() - } - } - - flush (flushFlag) { - if (this.ended) - return - - if (typeof flushFlag !== 'number') - flushFlag = this[_fullFlushFlag] - this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) - } - - end (chunk, encoding, cb) { - if (chunk) - this.write(chunk, encoding) - this.flush(this[_finishFlushFlag]) - this[_ended] = true - return super.end(null, null, cb) - } - - get ended () { - return this[_ended] - } - - write (chunk, encoding, cb) { - // process the chunk using the sync process - // then super.write() all the outputted chunks - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - - if (typeof chunk === 'string') - chunk = Buffer.from(chunk, encoding) - - if (this[_sawError]) - return - assert(this[_handle], 'zlib binding closed') - - // _processChunk tries to .close() the native handle after it's done, so we - // intercept that by temporarily making it a no-op. - const nativeHandle = this[_handle]._handle - const originalNativeClose = nativeHandle.close - nativeHandle.close = () => {} - const originalClose = this[_handle].close - this[_handle].close = () => {} - // It also calls `Buffer.concat()` at the end, which may be convenient - // for some, but which we are not interested in as it slows us down. - Buffer.concat = (args) => args - let result - try { - const flushFlag = typeof chunk[_flushFlag] === 'number' - ? chunk[_flushFlag] : this[_flushFlag] - result = this[_handle]._processChunk(chunk, flushFlag) - // if we don't throw, reset it back how it was - Buffer.concat = OriginalBufferConcat - } catch (err) { - // or if we do, put Buffer.concat() back before we emit error - // Error events call into user code, which may call Buffer.concat() - Buffer.concat = OriginalBufferConcat - this[_onError](new ZlibError(err)) - } finally { - if (this[_handle]) { - // Core zlib resets `_handle` to null after attempting to close the - // native handle. Our no-op handler prevented actual closure, but we - // need to restore the `._handle` property. - this[_handle]._handle = nativeHandle - nativeHandle.close = originalNativeClose - this[_handle].close = originalClose - // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. - this[_handle].removeAllListeners('error') - // make sure OUR error listener is still attached tho - } - } - - if (this[_handle]) - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - - let writeReturn - if (result) { - if (Array.isArray(result) && result.length > 0) { - // The first buffer is always `handle._outBuffer`, which would be - // re-used for later invocations; so, we always have to copy that one. - writeReturn = this[_superWrite](Buffer.from(result[0])) - for (let i = 1; i < result.length; i++) { - writeReturn = this[_superWrite](result[i]) - } - } else { - writeReturn = this[_superWrite](Buffer.from(result)) - } - } - - if (cb) - cb() - return writeReturn - } - - [_superWrite] (data) { - return super.write(data) - } -} - -class Zlib extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} - - opts.flush = opts.flush || constants.Z_NO_FLUSH - opts.finishFlush = opts.finishFlush || constants.Z_FINISH - super(opts, mode) - - this[_fullFlushFlag] = constants.Z_FULL_FLUSH - this[_level] = opts.level - this[_strategy] = opts.strategy - } - - params (level, strategy) { - if (this[_sawError]) - return - - if (!this[_handle]) - throw new Error('cannot switch params when binding is closed') - - // no way to test this without also not supporting params at all - /* istanbul ignore if */ - if (!this[_handle].params) - throw new Error('not supported in this implementation') - - if (this[_level] !== level || this[_strategy] !== strategy) { - this.flush(constants.Z_SYNC_FLUSH) - assert(this[_handle], 'zlib binding closed') - // .params() calls .flush(), but the latter is always async in the - // core zlib. We override .flush() temporarily to intercept that and - // flush synchronously. - const origFlush = this[_handle].flush - this[_handle].flush = (flushFlag, cb) => { - this.flush(flushFlag) - cb() - } - try { - this[_handle].params(level, strategy) - } finally { - this[_handle].flush = origFlush - } - /* istanbul ignore else */ - if (this[_handle]) { - this[_level] = level - this[_strategy] = strategy - } - } - } -} - -// minimal 2-byte header -class Deflate extends Zlib { - constructor (opts) { - super(opts, 'Deflate') - } -} - -class Inflate extends Zlib { - constructor (opts) { - super(opts, 'Inflate') - } -} - -// gzip - bigger header, same deflate compression -const _portable = Symbol('_portable') -class Gzip extends Zlib { - constructor (opts) { - super(opts, 'Gzip') - this[_portable] = opts && !!opts.portable - } - - [_superWrite] (data) { - if (!this[_portable]) - return super[_superWrite](data) - - // we'll always get the header emitted in one first chunk - // overwrite the OS indicator byte with 0xFF - this[_portable] = false - data[9] = 255 - return super[_superWrite](data) - } -} - -class Gunzip extends Zlib { - constructor (opts) { - super(opts, 'Gunzip') - } -} - -// raw - no header -class DeflateRaw extends Zlib { - constructor (opts) { - super(opts, 'DeflateRaw') - } -} - -class InflateRaw extends Zlib { - constructor (opts) { - super(opts, 'InflateRaw') - } -} - -// auto-detect header. -class Unzip extends Zlib { - constructor (opts) { - super(opts, 'Unzip') - } -} - -class Brotli extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} - - opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS - opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH - - super(opts, mode) - - this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH - } -} - -class BrotliCompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliCompress') - } -} - -class BrotliDecompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliDecompress') - } -} - -exports.Deflate = Deflate -exports.Inflate = Inflate -exports.Gzip = Gzip -exports.Gunzip = Gunzip -exports.DeflateRaw = DeflateRaw -exports.InflateRaw = InflateRaw -exports.Unzip = Unzip -/* istanbul ignore else */ -if (typeof realZlib.BrotliCompress === 'function') { - exports.BrotliCompress = BrotliCompress - exports.BrotliDecompress = BrotliDecompress -} else { - exports.BrotliCompress = exports.BrotliDecompress = class { - constructor () { - throw new Error('Brotli is not supported in this version of Node.js') - } - } -} - - -/***/ }), -/* 373 */ -/***/ (function(module, exports, __webpack_require__) { - -// Update with any zlib constants that are added or changed in the future. -// Node v6 didn't export this, so we just hard code the version and rely -// on all the other hard-coded values from zlib v4736. When node v6 -// support drops, we can just export the realZlibConstants object. -const realZlibConstants = __webpack_require__(145).constants || - /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } - -module.exports = Object.freeze(Object.assign(Object.create(null), { - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - Z_VERSION_ERROR: -6, - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - DEFLATE: 1, - INFLATE: 2, - GZIP: 3, - GUNZIP: 4, - DEFLATERAW: 5, - INFLATERAW: 6, - UNZIP: 7, - BROTLI_DECODE: 8, - BROTLI_ENCODE: 9, - Z_MIN_WINDOWBITS: 8, - Z_MAX_WINDOWBITS: 15, - Z_DEFAULT_WINDOWBITS: 15, - Z_MIN_CHUNK: 64, - Z_MAX_CHUNK: Infinity, - Z_DEFAULT_CHUNK: 16384, - Z_MIN_MEMLEVEL: 1, - Z_MAX_MEMLEVEL: 9, - Z_DEFAULT_MEMLEVEL: 8, - Z_MIN_LEVEL: -1, - Z_MAX_LEVEL: 9, - Z_DEFAULT_LEVEL: -1, - BROTLI_OPERATION_PROCESS: 0, - BROTLI_OPERATION_FLUSH: 1, - BROTLI_OPERATION_FINISH: 2, - BROTLI_OPERATION_EMIT_METADATA: 3, - BROTLI_MODE_GENERIC: 0, - BROTLI_MODE_TEXT: 1, - BROTLI_MODE_FONT: 2, - BROTLI_DEFAULT_MODE: 0, - BROTLI_MIN_QUALITY: 0, - BROTLI_MAX_QUALITY: 11, - BROTLI_DEFAULT_QUALITY: 11, - BROTLI_MIN_WINDOW_BITS: 10, - BROTLI_MAX_WINDOW_BITS: 24, - BROTLI_LARGE_MAX_WINDOW_BITS: 30, - BROTLI_DEFAULT_WINDOW: 22, - BROTLI_MIN_INPUT_BLOCK_BITS: 16, - BROTLI_MAX_INPUT_BLOCK_BITS: 24, - BROTLI_PARAM_MODE: 0, - BROTLI_PARAM_QUALITY: 1, - BROTLI_PARAM_LGWIN: 2, - BROTLI_PARAM_LGBLOCK: 3, - BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, - BROTLI_PARAM_SIZE_HINT: 5, - BROTLI_PARAM_LARGE_WINDOW: 6, - BROTLI_PARAM_NPOSTFIX: 7, - BROTLI_PARAM_NDIRECT: 8, - BROTLI_DECODER_RESULT_ERROR: 0, - BROTLI_DECODER_RESULT_SUCCESS: 1, - BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, - BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, - BROTLI_DECODER_NO_ERROR: 0, - BROTLI_DECODER_SUCCESS: 1, - BROTLI_DECODER_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, - BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, - BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, - BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, - BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, - BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, - BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, - BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, - BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, - BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, - BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, - BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, - BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, - BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, - BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, - BROTLI_DECODER_ERROR_UNREACHABLE: -31, -}, realZlibConstants)) - - -/***/ }), -/* 374 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const types = __webpack_require__(375) -const MiniPass = __webpack_require__(368) - -const SLURP = Symbol('slurp') -module.exports = class ReadEntry extends MiniPass { - constructor (header, ex, gex) { - super() - // read entries always start life paused. this is to avoid the - // situation where Minipass's auto-ending empty streams results - // in an entry ending before we're ready for it. - this.pause() - this.extended = ex - this.globalExtended = gex - this.header = header - this.startBlockSize = 512 * Math.ceil(header.size / 512) - this.blockRemain = this.startBlockSize - this.remain = header.size - this.type = header.type - this.meta = false - this.ignore = false - switch (this.type) { - case 'File': - case 'OldFile': - case 'Link': - case 'SymbolicLink': - case 'CharacterDevice': - case 'BlockDevice': - case 'Directory': - case 'FIFO': - case 'ContiguousFile': - case 'GNUDumpDir': - break - - case 'NextFileHasLongLinkpath': - case 'NextFileHasLongPath': - case 'OldGnuLongPath': - case 'GlobalExtendedHeader': - case 'ExtendedHeader': - case 'OldExtendedHeader': - this.meta = true - break - - // NOTE: gnutar and bsdtar treat unrecognized types as 'File' - // it may be worth doing the same, but with a warning. - default: - this.ignore = true - } - - this.path = header.path - this.mode = header.mode - if (this.mode) - this.mode = this.mode & 0o7777 - this.uid = header.uid - this.gid = header.gid - this.uname = header.uname - this.gname = header.gname - this.size = header.size - this.mtime = header.mtime - this.atime = header.atime - this.ctime = header.ctime - this.linkpath = header.linkpath - this.uname = header.uname - this.gname = header.gname - - if (ex) this[SLURP](ex) - if (gex) this[SLURP](gex, true) - } - - write (data) { - const writeLen = data.length - if (writeLen > this.blockRemain) - throw new Error('writing more to entry than is appropriate') - - const r = this.remain - const br = this.blockRemain - this.remain = Math.max(0, r - writeLen) - this.blockRemain = Math.max(0, br - writeLen) - if (this.ignore) - return true - - if (r >= writeLen) - return super.write(data) - - // r < writeLen - return super.write(data.slice(0, r)) - } - - [SLURP] (ex, global) { - for (let k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) - this[k] = ex[k] - } - } -} - - -/***/ }), -/* 375 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// map types from key to human-friendly name -exports.name = new Map([ - ['0', 'File'], - // same as File - ['', 'OldFile'], - ['1', 'Link'], - ['2', 'SymbolicLink'], - // Devices and FIFOs aren't fully supported - // they are parsed, but skipped when unpacking - ['3', 'CharacterDevice'], - ['4', 'BlockDevice'], - ['5', 'Directory'], - ['6', 'FIFO'], - // same as File - ['7', 'ContiguousFile'], - // pax headers - ['g', 'GlobalExtendedHeader'], - ['x', 'ExtendedHeader'], - // vendor-specific stuff - // skip - ['A', 'SolarisACL'], - // like 5, but with data, which should be skipped - ['D', 'GNUDumpDir'], - // metadata only, skip - ['I', 'Inode'], - // data = link path of next file - ['K', 'NextFileHasLongLinkpath'], - // data = path of next file - ['L', 'NextFileHasLongPath'], - // skip - ['M', 'ContinuationFile'], - // like L - ['N', 'OldGnuLongPath'], - // skip - ['S', 'SparseFile'], - // skip - ['V', 'TapeVolumeHeader'], - // like x - ['X', 'OldExtendedHeader'] -]) - -// map the other direction -exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) - - -/***/ }), -/* 376 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const MiniPass = __webpack_require__(368) -const Pax = __webpack_require__(377) -const Header = __webpack_require__(378) -const ReadEntry = __webpack_require__(374) -const fs = __webpack_require__(66) -const path = __webpack_require__(82) - -const types = __webpack_require__(375) -const maxReadSize = 16 * 1024 * 1024 -const PROCESS = Symbol('process') -const FILE = Symbol('file') -const DIRECTORY = Symbol('directory') -const SYMLINK = Symbol('symlink') -const HARDLINK = Symbol('hardlink') -const HEADER = Symbol('header') -const READ = Symbol('read') -const LSTAT = Symbol('lstat') -const ONLSTAT = Symbol('onlstat') -const ONREAD = Symbol('onread') -const ONREADLINK = Symbol('onreadlink') -const OPENFILE = Symbol('openfile') -const ONOPENFILE = Symbol('onopenfile') -const CLOSE = Symbol('close') -const MODE = Symbol('mode') -const warner = __webpack_require__(380) -const winchars = __webpack_require__(381) - -const modeFix = __webpack_require__(382) - -const WriteEntry = warner(class WriteEntry extends MiniPass { - constructor (p, opt) { - opt = opt || {} - super(opt) - if (typeof p !== 'string') - throw new TypeError('path is required') - this.path = p - // suppress atime, ctime, uid, gid, uname, gname - this.portable = !!opt.portable - // until node has builtin pwnam functions, this'll have to do - this.myuid = process.getuid && process.getuid() - this.myuser = process.env.USER || '' - this.maxReadSize = opt.maxReadSize || maxReadSize - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.preservePaths = !!opt.preservePaths - this.cwd = opt.cwd || process.cwd() - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null - - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - - let pathWarn = false - if (!this.preservePaths && path.win32.isAbsolute(p)) { - // absolutes on posix are also absolutes on win32 - // so we only need to test this one to get both - const parsed = path.win32.parse(p) - this.path = p.substr(parsed.root.length) - pathWarn = parsed.root - } - - this.win32 = !!opt.win32 || process.platform === 'win32' - if (this.win32) { - this.path = winchars.decode(this.path.replace(/\\/g, '/')) - p = p.replace(/\\/g, '/') - } - - this.absolute = opt.absolute || path.resolve(this.cwd, p) - - if (this.path === '') - this.path = './' - - if (pathWarn) { - this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path, - }) - } - - if (this.statCache.has(this.absolute)) - this[ONLSTAT](this.statCache.get(this.absolute)) - else - this[LSTAT]() - } - - [LSTAT] () { - fs.lstat(this.absolute, (er, stat) => { - if (er) - return this.emit('error', er) - this[ONLSTAT](stat) - }) - } - - [ONLSTAT] (stat) { - this.statCache.set(this.absolute, stat) - this.stat = stat - if (!stat.isFile()) - stat.size = 0 - this.type = getType(stat) - this.emit('stat', stat) - this[PROCESS]() - } - - [PROCESS] () { - switch (this.type) { - case 'File': return this[FILE]() - case 'Directory': return this[DIRECTORY]() - case 'SymbolicLink': return this[SYMLINK]() - // unsupported types are ignored. - default: return this.end() - } - } - - [MODE] (mode) { - return modeFix(mode, this.type === 'Directory', this.portable) - } - - [HEADER] () { - if (this.type === 'Directory' && this.portable) - this.noMtime = true - - this.header = new Header({ - path: this.path, - linkpath: this.linkpath, - // only the permissions and setuid/setgid/sticky bitflags - // not the higher-order bits that specify file type - mode: this[MODE](this.stat.mode), - uid: this.portable ? null : this.stat.uid, - gid: this.portable ? null : this.stat.gid, - size: this.stat.size, - mtime: this.noMtime ? null : this.mtime || this.stat.mtime, - type: this.type, - uname: this.portable ? null : - this.stat.uid === this.myuid ? this.myuser : '', - atime: this.portable ? null : this.stat.atime, - ctime: this.portable ? null : this.stat.ctime - }) - - if (this.header.encode() && !this.noPax) - this.write(new Pax({ - atime: this.portable ? null : this.header.atime, - ctime: this.portable ? null : this.header.ctime, - gid: this.portable ? null : this.header.gid, - mtime: this.noMtime ? null : this.mtime || this.header.mtime, - path: this.path, - linkpath: this.linkpath, - size: this.header.size, - uid: this.portable ? null : this.header.uid, - uname: this.portable ? null : this.header.uname, - dev: this.portable ? null : this.stat.dev, - ino: this.portable ? null : this.stat.ino, - nlink: this.portable ? null : this.stat.nlink - }).encode()) - this.write(this.header.block) - } - - [DIRECTORY] () { - if (this.path.substr(-1) !== '/') - this.path += '/' - this.stat.size = 0 - this[HEADER]() - this.end() - } - - [SYMLINK] () { - fs.readlink(this.absolute, (er, linkpath) => { - if (er) - return this.emit('error', er) - this[ONREADLINK](linkpath) - }) - } - - [ONREADLINK] (linkpath) { - this.linkpath = linkpath.replace(/\\/g, '/') - this[HEADER]() - this.end() - } - - [HARDLINK] (linkpath) { - this.type = 'Link' - this.linkpath = path.relative(this.cwd, linkpath).replace(/\\/g, '/') - this.stat.size = 0 - this[HEADER]() - this.end() - } - - [FILE] () { - if (this.stat.nlink > 1) { - const linkKey = this.stat.dev + ':' + this.stat.ino - if (this.linkCache.has(linkKey)) { - const linkpath = this.linkCache.get(linkKey) - if (linkpath.indexOf(this.cwd) === 0) - return this[HARDLINK](linkpath) - } - this.linkCache.set(linkKey, this.absolute) - } - - this[HEADER]() - if (this.stat.size === 0) - return this.end() - - this[OPENFILE]() - } - - [OPENFILE] () { - fs.open(this.absolute, 'r', (er, fd) => { - if (er) - return this.emit('error', er) - this[ONOPENFILE](fd) - }) - } - - [ONOPENFILE] (fd) { - const blockLen = 512 * Math.ceil(this.stat.size / 512) - const bufLen = Math.min(blockLen, this.maxReadSize) - const buf = Buffer.allocUnsafe(bufLen) - this[READ](fd, buf, 0, buf.length, 0, this.stat.size, blockLen) - } - - [READ] (fd, buf, offset, length, pos, remain, blockRemain) { - fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { - if (er) { - // ignoring the error from close(2) is a bad practice, but at - // this point we already have an error, don't need another one - return this[CLOSE](fd, () => this.emit('error', er)) - } - this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead) - }) - } - - [CLOSE] (fd, cb) { - fs.close(fd, cb) - } - - [ONREAD] (fd, buf, offset, length, pos, remain, blockRemain, bytesRead) { - if (bytesRead <= 0 && remain > 0) { - const er = new Error('encountered unexpected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](fd, () => this.emit('error', er)) - } - - if (bytesRead > remain) { - const er = new Error('did not encounter expected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](fd, () => this.emit('error', er)) - } - - // null out the rest of the buffer, if we could fit the block padding - if (bytesRead === remain) { - for (let i = bytesRead; i < length && bytesRead < blockRemain; i++) { - buf[i + offset] = 0 - bytesRead ++ - remain ++ - } - } - - const writeBuf = offset === 0 && bytesRead === buf.length ? - buf : buf.slice(offset, offset + bytesRead) - remain -= bytesRead - blockRemain -= bytesRead - pos += bytesRead - offset += bytesRead - - this.write(writeBuf) - - if (!remain) { - if (blockRemain) - this.write(Buffer.alloc(blockRemain)) - return this[CLOSE](fd, er => er ? this.emit('error', er) : this.end()) - } - - if (offset >= length) { - buf = Buffer.allocUnsafe(length) - offset = 0 - } - length = buf.length - offset - this[READ](fd, buf, offset, length, pos, remain, blockRemain) - } -}) - -class WriteEntrySync extends WriteEntry { - constructor (path, opt) { - super(path, opt) - } - - [LSTAT] () { - this[ONLSTAT](fs.lstatSync(this.absolute)) - } - - [SYMLINK] () { - this[ONREADLINK](fs.readlinkSync(this.absolute)) - } - - [OPENFILE] () { - this[ONOPENFILE](fs.openSync(this.absolute, 'r')) - } - - [READ] (fd, buf, offset, length, pos, remain, blockRemain) { - let threw = true - try { - const bytesRead = fs.readSync(fd, buf, offset, length, pos) - this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead) - threw = false - } finally { - // ignoring the error from close(2) is a bad practice, but at - // this point we already have an error, don't need another one - if (threw) - try { this[CLOSE](fd, () => {}) } catch (er) {} - } - } - - [CLOSE] (fd, cb) { - fs.closeSync(fd) - cb() - } -} - -const WriteEntryTar = warner(class WriteEntryTar extends MiniPass { - constructor (readEntry, opt) { - opt = opt || {} - super(opt) - this.preservePaths = !!opt.preservePaths - this.portable = !!opt.portable - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - - this.readEntry = readEntry - this.type = readEntry.type - if (this.type === 'Directory' && this.portable) - this.noMtime = true - - this.path = readEntry.path - this.mode = this[MODE](readEntry.mode) - this.uid = this.portable ? null : readEntry.uid - this.gid = this.portable ? null : readEntry.gid - this.uname = this.portable ? null : readEntry.uname - this.gname = this.portable ? null : readEntry.gname - this.size = readEntry.size - this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime - this.atime = this.portable ? null : readEntry.atime - this.ctime = this.portable ? null : readEntry.ctime - this.linkpath = readEntry.linkpath - - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - - let pathWarn = false - if (path.isAbsolute(this.path) && !this.preservePaths) { - const parsed = path.parse(this.path) - pathWarn = parsed.root - this.path = this.path.substr(parsed.root.length) - } - - this.remain = readEntry.size - this.blockRemain = readEntry.startBlockSize - - this.header = new Header({ - path: this.path, - linkpath: this.linkpath, - // only the permissions and setuid/setgid/sticky bitflags - // not the higher-order bits that specify file type - mode: this.mode, - uid: this.portable ? null : this.uid, - gid: this.portable ? null : this.gid, - size: this.size, - mtime: this.noMtime ? null : this.mtime, - type: this.type, - uname: this.portable ? null : this.uname, - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime - }) - - if (pathWarn) { - this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path, - }) - } - - if (this.header.encode() && !this.noPax) - super.write(new Pax({ - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime, - gid: this.portable ? null : this.gid, - mtime: this.noMtime ? null : this.mtime, - path: this.path, - linkpath: this.linkpath, - size: this.size, - uid: this.portable ? null : this.uid, - uname: this.portable ? null : this.uname, - dev: this.portable ? null : this.readEntry.dev, - ino: this.portable ? null : this.readEntry.ino, - nlink: this.portable ? null : this.readEntry.nlink - }).encode()) - - super.write(this.header.block) - readEntry.pipe(this) - } - - [MODE] (mode) { - return modeFix(mode, this.type === 'Directory', this.portable) - } - - write (data) { - const writeLen = data.length - if (writeLen > this.blockRemain) - throw new Error('writing more to entry than is appropriate') - this.blockRemain -= writeLen - return super.write(data) - } - - end () { - if (this.blockRemain) - this.write(Buffer.alloc(this.blockRemain)) - return super.end() - } -}) - -WriteEntry.Sync = WriteEntrySync -WriteEntry.Tar = WriteEntryTar - -const getType = stat => - stat.isFile() ? 'File' - : stat.isDirectory() ? 'Directory' - : stat.isSymbolicLink() ? 'SymbolicLink' - : 'Unsupported' - -module.exports = WriteEntry - - -/***/ }), -/* 377 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const Header = __webpack_require__(378) -const path = __webpack_require__(82) - -class Pax { - constructor (obj, global) { - this.atime = obj.atime || null - this.charset = obj.charset || null - this.comment = obj.comment || null - this.ctime = obj.ctime || null - this.gid = obj.gid || null - this.gname = obj.gname || null - this.linkpath = obj.linkpath || null - this.mtime = obj.mtime || null - this.path = obj.path || null - this.size = obj.size || null - this.uid = obj.uid || null - this.uname = obj.uname || null - this.dev = obj.dev || null - this.ino = obj.ino || null - this.nlink = obj.nlink || null - this.global = global || false - } - - encode () { - const body = this.encodeBody() - if (body === '') - return null - - const bodyLen = Buffer.byteLength(body) - // round up to 512 bytes - // add 512 for header - const bufLen = 512 * Math.ceil(1 + bodyLen / 512) - const buf = Buffer.allocUnsafe(bufLen) - - // 0-fill the header section, it might not hit every field - for (let i = 0; i < 512; i++) { - buf[i] = 0 - } - - new Header({ - // XXX split the path - // then the path should be PaxHeader + basename, but less than 99, - // prepend with the dirname - path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), - mode: this.mode || 0o644, - uid: this.uid || null, - gid: this.gid || null, - size: bodyLen, - mtime: this.mtime || null, - type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', - linkpath: '', - uname: this.uname || '', - gname: this.gname || '', - devmaj: 0, - devmin: 0, - atime: this.atime || null, - ctime: this.ctime || null - }).encode(buf) - - buf.write(body, 512, bodyLen, 'utf8') - - // null pad after the body - for (let i = bodyLen + 512; i < buf.length; i++) { - buf[i] = 0 - } - - return buf - } - - encodeBody () { - return ( - this.encodeField('path') + - this.encodeField('ctime') + - this.encodeField('atime') + - this.encodeField('dev') + - this.encodeField('ino') + - this.encodeField('nlink') + - this.encodeField('charset') + - this.encodeField('comment') + - this.encodeField('gid') + - this.encodeField('gname') + - this.encodeField('linkpath') + - this.encodeField('mtime') + - this.encodeField('size') + - this.encodeField('uid') + - this.encodeField('uname') - ) - } - - encodeField (field) { - if (this[field] === null || this[field] === undefined) - return '' - const v = this[field] instanceof Date ? this[field].getTime() / 1000 - : this[field] - const s = ' ' + - (field === 'dev' || field === 'ino' || field === 'nlink' - ? 'SCHILY.' : '') + - field + '=' + v + '\n' - const byteLen = Buffer.byteLength(s) - // the digits includes the length of the digits in ascii base-10 - // so if it's 9 characters, then adding 1 for the 9 makes it 10 - // which makes it 11 chars. - let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 - if (byteLen + digits >= Math.pow(10, digits)) - digits += 1 - const len = digits + byteLen - return len + s - } -} - -Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) - -const merge = (a, b) => - b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a - -const parseKV = string => - string - .replace(/\n$/, '') - .split('\n') - .reduce(parseKVLine, Object.create(null)) - -const parseKVLine = (set, line) => { - const n = parseInt(line, 10) - - // XXX Values with \n in them will fail this. - // Refactor to not be a naive line-by-line parse. - if (n !== Buffer.byteLength(line) + 1) - return set - - line = line.substr((n + ' ').length) - const kv = line.split('=') - const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') - if (!k) - return set - - const v = kv.join('=') - set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) - ? new Date(v * 1000) - : /^[0-9]+$/.test(v) ? +v - : v - return set -} - -module.exports = Pax - - -/***/ }), -/* 378 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// parse a 512-byte header block to a data object, or vice-versa -// encode returns `true` if a pax extended header is needed, because -// the data could not be faithfully encoded in a simple header. -// (Also, check header.needPax to see if it needs a pax header.) - -const types = __webpack_require__(375) -const pathModule = __webpack_require__(82).posix -const large = __webpack_require__(379) - -const SLURP = Symbol('slurp') -const TYPE = Symbol('type') - -class Header { - constructor (data, off, ex, gex) { - this.cksumValid = false - this.needPax = false - this.nullBlock = false - - this.block = null - this.path = null - this.mode = null - this.uid = null - this.gid = null - this.size = null - this.mtime = null - this.cksum = null - this[TYPE] = '0' - this.linkpath = null - this.uname = null - this.gname = null - this.devmaj = 0 - this.devmin = 0 - this.atime = null - this.ctime = null - - if (Buffer.isBuffer(data)) - this.decode(data, off || 0, ex, gex) - else if (data) - this.set(data) - } - - decode (buf, off, ex, gex) { - if (!off) - off = 0 - - if (!buf || !(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - this.path = decString(buf, off, 100) - this.mode = decNumber(buf, off + 100, 8) - this.uid = decNumber(buf, off + 108, 8) - this.gid = decNumber(buf, off + 116, 8) - this.size = decNumber(buf, off + 124, 12) - this.mtime = decDate(buf, off + 136, 12) - this.cksum = decNumber(buf, off + 148, 12) - - // if we have extended or global extended headers, apply them now - // See https://github.com/npm/node-tar/pull/187 - this[SLURP](ex) - this[SLURP](gex, true) - - // old tar versions marked dirs as a file with a trailing / - this[TYPE] = decString(buf, off + 156, 1) - if (this[TYPE] === '') - this[TYPE] = '0' - if (this[TYPE] === '0' && this.path.substr(-1) === '/') - this[TYPE] = '5' - - // tar implementations sometimes incorrectly put the stat(dir).size - // as the size in the tarball, even though Directory entries are - // not able to have any body at all. In the very rare chance that - // it actually DOES have a body, we weren't going to do anything with - // it anyway, and it'll just be a warning about an invalid header. - if (this[TYPE] === '5') - this.size = 0 - - this.linkpath = decString(buf, off + 157, 100) - if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { - this.uname = decString(buf, off + 265, 32) - this.gname = decString(buf, off + 297, 32) - this.devmaj = decNumber(buf, off + 329, 8) - this.devmin = decNumber(buf, off + 337, 8) - if (buf[off + 475] !== 0) { - // definitely a prefix, definitely >130 chars. - const prefix = decString(buf, off + 345, 155) - this.path = prefix + '/' + this.path - } else { - const prefix = decString(buf, off + 345, 130) - if (prefix) - this.path = prefix + '/' + this.path - this.atime = decDate(buf, off + 476, 12) - this.ctime = decDate(buf, off + 488, 12) - } - } - - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksumValid = sum === this.cksum - if (this.cksum === null && sum === 8 * 0x20) - this.nullBlock = true - } - - [SLURP] (ex, global) { - for (let k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) - this[k] = ex[k] - } - } - - encode (buf, off) { - if (!buf) { - buf = this.block = Buffer.alloc(512) - off = 0 - } - - if (!off) - off = 0 - - if (!(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - const prefixSize = this.ctime || this.atime ? 130 : 155 - const split = splitPrefix(this.path || '', prefixSize) - const path = split[0] - const prefix = split[1] - this.needPax = split[2] - - this.needPax = encString(buf, off, 100, path) || this.needPax - this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax - this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax - this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax - this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax - this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax - buf[off + 156] = this[TYPE].charCodeAt(0) - this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax - buf.write('ustar\u000000', off + 257, 8) - this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax - this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax - this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax - this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax - this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax - if (buf[off + 475] !== 0) - this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax - else { - this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax - this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax - this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax - } - - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksum = sum - encNumber(buf, off + 148, 8, this.cksum) - this.cksumValid = true - - return this.needPax - } - - set (data) { - for (let i in data) { - if (data[i] !== null && data[i] !== undefined) - this[i] = data[i] - } - } - - get type () { - return types.name.get(this[TYPE]) || this[TYPE] - } - - get typeKey () { - return this[TYPE] - } - - set type (type) { - if (types.code.has(type)) - this[TYPE] = types.code.get(type) - else - this[TYPE] = type - } -} - -const splitPrefix = (p, prefixSize) => { - const pathSize = 100 - let pp = p - let prefix = '' - let ret - const root = pathModule.parse(p).root || '.' - - if (Buffer.byteLength(pp) < pathSize) - ret = [pp, prefix, false] - else { - // first set prefix to the dir, and path to the base - prefix = pathModule.dirname(pp) - pp = pathModule.basename(pp) - - do { - // both fit! - if (Buffer.byteLength(pp) <= pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp, prefix, false] - - // prefix fits in prefix, but path doesn't fit in path - else if (Buffer.byteLength(pp) > pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp.substr(0, pathSize - 1), prefix, true] - - else { - // make path take a bit from prefix - pp = pathModule.join(pathModule.basename(prefix), pp) - prefix = pathModule.dirname(prefix) - } - } while (prefix !== root && !ret) - - // at this point, found no resolution, just truncate - if (!ret) - ret = [p.substr(0, pathSize - 1), '', true] - } - return ret -} - -const decString = (buf, off, size) => - buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') - -const decDate = (buf, off, size) => - numToDate(decNumber(buf, off, size)) - -const numToDate = num => num === null ? null : new Date(num * 1000) - -const decNumber = (buf, off, size) => - buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) - : decSmallNumber(buf, off, size) - -const nanNull = value => isNaN(value) ? null : value - -const decSmallNumber = (buf, off, size) => - nanNull(parseInt( - buf.slice(off, off + size) - .toString('utf8').replace(/\0.*$/, '').trim(), 8)) - -// the maximum encodable as a null-terminated octal, by field size -const MAXNUM = { - 12: 0o77777777777, - 8 : 0o7777777 -} - -const encNumber = (buf, off, size, number) => - number === null ? false : - number > MAXNUM[size] || number < 0 - ? (large.encode(number, buf.slice(off, off + size)), true) - : (encSmallNumber(buf, off, size, number), false) - -const encSmallNumber = (buf, off, size, number) => - buf.write(octalString(number, size), off, size, 'ascii') - -const octalString = (number, size) => - padOctal(Math.floor(number).toString(8), size) - -const padOctal = (string, size) => - (string.length === size - 1 ? string - : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' - -const encDate = (buf, off, size, date) => - date === null ? false : - encNumber(buf, off, size, date.getTime() / 1000) - -// enough to fill the longest string we've got -const NULLS = new Array(156).join('\0') -// pad with nulls, return true if it's longer or non-ascii -const encString = (buf, off, size, string) => - string === null ? false : - (buf.write(string + NULLS, off, size, 'utf8'), - string.length !== Buffer.byteLength(string) || string.length > size) - -module.exports = Header - - -/***/ }), -/* 379 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Tar can encode large and negative numbers using a leading byte of -// 0xff for negative, and 0x80 for positive. - -const encode = exports.encode = (num, buf) => { - if (!Number.isSafeInteger(num)) - // The number is so large that javascript cannot represent it with integer - // precision. - throw Error('cannot encode number outside of javascript safe integer range') - else if (num < 0) - encodeNegative(num, buf) - else - encodePositive(num, buf) - return buf -} - -const encodePositive = (num, buf) => { - buf[0] = 0x80 - - for (var i = buf.length; i > 1; i--) { - buf[i-1] = num & 0xff - num = Math.floor(num / 0x100) - } -} - -const encodeNegative = (num, buf) => { - buf[0] = 0xff - var flipped = false - num = num * -1 - for (var i = buf.length; i > 1; i--) { - var byte = num & 0xff - num = Math.floor(num / 0x100) - if (flipped) - buf[i-1] = onesComp(byte) - else if (byte === 0) - buf[i-1] = 0 - else { - flipped = true - buf[i-1] = twosComp(byte) - } - } -} - -const parse = exports.parse = (buf) => { - var post = buf[buf.length - 1] - var pre = buf[0] - var value; - if (pre === 0x80) - value = pos(buf.slice(1, buf.length)) - else if (pre === 0xff) - value = twos(buf) - else - throw Error('invalid base256 encoding') - - if (!Number.isSafeInteger(value)) - // The number is so large that javascript cannot represent it with integer - // precision. - throw Error('parsed number outside of javascript safe integer range') - - return value -} - -const twos = (buf) => { - var len = buf.length - var sum = 0 - var flipped = false - for (var i = len - 1; i > -1; i--) { - var byte = buf[i] - var f - if (flipped) - f = onesComp(byte) - else if (byte === 0) - f = byte - else { - flipped = true - f = twosComp(byte) - } - if (f !== 0) - sum -= f * Math.pow(256, len - i - 1) - } - return sum -} - -const pos = (buf) => { - var len = buf.length - var sum = 0 - for (var i = len - 1; i > -1; i--) { - var byte = buf[i] - if (byte !== 0) - sum += byte * Math.pow(256, len - i - 1) - } - return sum -} - -const onesComp = byte => (0xff ^ byte) & 0xff - -const twosComp = byte => ((0xff ^ byte) + 1) & 0xff - - -/***/ }), -/* 380 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = Base => class extends Base { - warn (code, message, data = {}) { - if (this.file) - data.file = this.file - if (this.cwd) - data.cwd = this.cwd - data.code = message instanceof Error && message.code || code - data.tarCode = code - if (!this.strict && data.recoverable !== false) { - if (message instanceof Error) { - data = Object.assign(message, data) - message = message.message - } - this.emit('warn', data.tarCode, message, data) - } else if (message instanceof Error) { - this.emit('error', Object.assign(message, data)) - } else - this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) - } -} - - -/***/ }), -/* 381 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// When writing files on Windows, translate the characters to their -// 0xf000 higher-encoded versions. - -const raw = [ - '|', - '<', - '>', - '?', - ':' -] - -const win = raw.map(char => - String.fromCharCode(0xf000 + char.charCodeAt(0))) - -const toWin = new Map(raw.map((char, i) => [char, win[i]])) -const toRaw = new Map(win.map((char, i) => [char, raw[i]])) - -module.exports = { - encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), - decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s) -} - - -/***/ }), -/* 382 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = (mode, isDir, portable) => { - mode &= 0o7777 - - // in portable mode, use the minimum reasonable umask - // if this system creates files with 0o664 by default - // (as some linux distros do), then we'll write the - // archive with 0o644 instead. Also, don't ever create - // a file that is not readable/writable by the owner. - if (portable) { - mode = (mode | 0o600) &~0o22 - } - - // if dirs are readable, then they should be listable - if (isDir) { - if (mode & 0o400) - mode |= 0o100 - if (mode & 0o40) - mode |= 0o10 - if (mode & 0o4) - mode |= 0o1 - } - return mode -} - - -/***/ }), -/* 383 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const MiniPass = __webpack_require__(368) -const EE = __webpack_require__(198).EventEmitter -const fs = __webpack_require__(66) - -let writev = fs.writev -/* istanbul ignore next */ -if (!writev) { - // This entire block can be removed if support for earlier than Node.js - // 12.9.0 is not needed. - const binding = process.binding('fs') - const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback - - writev = (fd, iovec, pos, cb) => { - const done = (er, bw) => cb(er, bw, iovec) - const req = new FSReqWrap() - req.oncomplete = done - binding.writeBuffers(fd, iovec, pos, req) - } -} - -const _autoClose = Symbol('_autoClose') -const _close = Symbol('_close') -const _ended = Symbol('_ended') -const _fd = Symbol('_fd') -const _finished = Symbol('_finished') -const _flags = Symbol('_flags') -const _flush = Symbol('_flush') -const _handleChunk = Symbol('_handleChunk') -const _makeBuf = Symbol('_makeBuf') -const _mode = Symbol('_mode') -const _needDrain = Symbol('_needDrain') -const _onerror = Symbol('_onerror') -const _onopen = Symbol('_onopen') -const _onread = Symbol('_onread') -const _onwrite = Symbol('_onwrite') -const _open = Symbol('_open') -const _path = Symbol('_path') -const _pos = Symbol('_pos') -const _queue = Symbol('_queue') -const _read = Symbol('_read') -const _readSize = Symbol('_readSize') -const _reading = Symbol('_reading') -const _remain = Symbol('_remain') -const _size = Symbol('_size') -const _write = Symbol('_write') -const _writing = Symbol('_writing') -const _defaultFlag = Symbol('_defaultFlag') -const _errored = Symbol('_errored') - -class ReadStream extends MiniPass { - constructor (path, opt) { - opt = opt || {} - super(opt) - - this.readable = true - this.writable = false - - if (typeof path !== 'string') - throw new TypeError('path must be a string') - - this[_errored] = false - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_path] = path - this[_readSize] = opt.readSize || 16*1024*1024 - this[_reading] = false - this[_size] = typeof opt.size === 'number' ? opt.size : Infinity - this[_remain] = this[_size] - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true - - if (typeof this[_fd] === 'number') - this[_read]() - else - this[_open]() - } - - get fd () { return this[_fd] } - get path () { return this[_path] } - - write () { - throw new TypeError('this is a readable stream') - } - - end () { - throw new TypeError('this is a readable stream') - } - - [_open] () { - fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) - } - - [_onopen] (er, fd) { - if (er) - this[_onerror](er) - else { - this[_fd] = fd - this.emit('open', fd) - this[_read]() - } - } - - [_makeBuf] () { - return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) - } - - [_read] () { - if (!this[_reading]) { - this[_reading] = true - const buf = this[_makeBuf]() - /* istanbul ignore if */ - if (buf.length === 0) - return process.nextTick(() => this[_onread](null, 0, buf)) - fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => - this[_onread](er, br, buf)) - } - } - - [_onread] (er, br, buf) { - this[_reading] = false - if (er) - this[_onerror](er) - else if (this[_handleChunk](br, buf)) - this[_read]() - } - - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) - } - } - - [_onerror] (er) { - this[_reading] = true - this[_close]() - this.emit('error', er) - } - - [_handleChunk] (br, buf) { - let ret = false - // no effect if infinite - this[_remain] -= br - if (br > 0) - ret = super.write(br < buf.length ? buf.slice(0, br) : buf) - - if (br === 0 || this[_remain] <= 0) { - ret = false - this[_close]() - super.end() - } - - return ret - } - - emit (ev, data) { - switch (ev) { - case 'prefinish': - case 'finish': - break - - case 'drain': - if (typeof this[_fd] === 'number') - this[_read]() - break - - case 'error': - if (this[_errored]) - return - this[_errored] = true - return super.emit(ev, data) - - default: - return super.emit(ev, data) - } - } -} - -class ReadStreamSync extends ReadStream { - [_open] () { - let threw = true - try { - this[_onopen](null, fs.openSync(this[_path], 'r')) - threw = false - } finally { - if (threw) - this[_close]() - } - } - - [_read] () { - let threw = true - try { - if (!this[_reading]) { - this[_reading] = true - do { - const buf = this[_makeBuf]() - /* istanbul ignore next */ - const br = buf.length === 0 ? 0 - : fs.readSync(this[_fd], buf, 0, buf.length, null) - if (!this[_handleChunk](br, buf)) - break - } while (true) - this[_reading] = false - } - threw = false - } finally { - if (threw) - this[_close]() - } - } - - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } -} - -class WriteStream extends EE { - constructor (path, opt) { - opt = opt || {} - super(opt) - this.readable = false - this.writable = true - this[_errored] = false - this[_writing] = false - this[_ended] = false - this[_needDrain] = false - this[_queue] = [] - this[_path] = path - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_mode] = opt.mode === undefined ? 0o666 : opt.mode - this[_pos] = typeof opt.start === 'number' ? opt.start : null - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true - - // truncating makes no sense when writing into the middle - const defaultFlag = this[_pos] !== null ? 'r+' : 'w' - this[_defaultFlag] = opt.flags === undefined - this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags - - if (this[_fd] === null) - this[_open]() - } - - emit (ev, data) { - if (ev === 'error') { - if (this[_errored]) - return - this[_errored] = true - } - return super.emit(ev, data) - } - - - get fd () { return this[_fd] } - get path () { return this[_path] } - - [_onerror] (er) { - this[_close]() - this[_writing] = true - this.emit('error', er) - } - - [_open] () { - fs.open(this[_path], this[_flags], this[_mode], - (er, fd) => this[_onopen](er, fd)) - } - - [_onopen] (er, fd) { - if (this[_defaultFlag] && - this[_flags] === 'r+' && - er && er.code === 'ENOENT') { - this[_flags] = 'w' - this[_open]() - } else if (er) - this[_onerror](er) - else { - this[_fd] = fd - this.emit('open', fd) - this[_flush]() - } - } - - end (buf, enc) { - if (buf) - this.write(buf, enc) - - this[_ended] = true - - // synthetic after-write logic, where drain/finish live - if (!this[_writing] && !this[_queue].length && - typeof this[_fd] === 'number') - this[_onwrite](null, 0) - return this - } - - write (buf, enc) { - if (typeof buf === 'string') - buf = Buffer.from(buf, enc) - - if (this[_ended]) { - this.emit('error', new Error('write() after end()')) - return false - } - - if (this[_fd] === null || this[_writing] || this[_queue].length) { - this[_queue].push(buf) - this[_needDrain] = true - return false - } - - this[_writing] = true - this[_write](buf) - return true - } - - [_write] (buf) { - fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => - this[_onwrite](er, bw)) - } - - [_onwrite] (er, bw) { - if (er) - this[_onerror](er) - else { - if (this[_pos] !== null) - this[_pos] += bw - if (this[_queue].length) - this[_flush]() - else { - this[_writing] = false - - if (this[_ended] && !this[_finished]) { - this[_finished] = true - this[_close]() - this.emit('finish') - } else if (this[_needDrain]) { - this[_needDrain] = false - this.emit('drain') - } - } - } - } - - [_flush] () { - if (this[_queue].length === 0) { - if (this[_ended]) - this[_onwrite](null, 0) - } else if (this[_queue].length === 1) - this[_write](this[_queue].pop()) - else { - const iovec = this[_queue] - this[_queue] = [] - writev(this[_fd], iovec, this[_pos], - (er, bw) => this[_onwrite](er, bw)) - } - } - - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) - } - } -} - -class WriteStreamSync extends WriteStream { - [_open] () { - let fd - // only wrap in a try{} block if we know we'll retry, to avoid - // the rethrow obscuring the error's source frame in most cases. - if (this[_defaultFlag] && this[_flags] === 'r+') { - try { - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - } catch (er) { - if (er.code === 'ENOENT') { - this[_flags] = 'w' - return this[_open]() - } else - throw er - } - } else - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - - this[_onopen](null, fd) - } - - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } - - [_write] (buf) { - // throw the original, but try to close if it fails - let threw = true - try { - this[_onwrite](null, - fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) - threw = false - } finally { - if (threw) - try { this[_close]() } catch (_) {} - } - } -} - -exports.ReadStream = ReadStream -exports.ReadStreamSync = ReadStreamSync - -exports.WriteStream = WriteStream -exports.WriteStreamSync = WriteStreamSync - - -/***/ }), -/* 384 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// XXX: This shares a lot in common with extract.js -// maybe some DRY opportunity here? - -// tar -t -const hlo = __webpack_require__(366) -const Parser = __webpack_require__(385) -const fs = __webpack_require__(66) -const fsm = __webpack_require__(383) -const path = __webpack_require__(82) - -const t = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} - - if (typeof files === 'function') - cb = files, files = null - - if (!files) - files = [] - else - files = Array.from(files) - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') - - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') - - if (files.length) - filesFilter(opt, files) - - if (!opt.noResume) - onentryFunction(opt) - - return opt.file && opt.sync ? listFileSync(opt) - : opt.file ? listFile(opt, cb) - : list(opt) -} - -const onentryFunction = opt => { - const onentry = opt.onentry - opt.onentry = onentry ? e => { - onentry(e) - e.resume() - } : e => e.resume() -} - -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter - - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) - - map.set(file, ret) - return ret - } - - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) -} - -const listFileSync = opt => { - const p = list(opt) - const file = opt.file - let threw = true - let fd - try { - const stat = fs.statSync(file) - const readSize = opt.maxReadSize || 16*1024*1024 - if (stat.size < readSize) { - p.end(fs.readFileSync(file)) - } else { - let pos = 0 - const buf = Buffer.allocUnsafe(readSize) - fd = fs.openSync(file, 'r') - while (pos < stat.size) { - let bytesRead = fs.readSync(fd, buf, 0, readSize, pos) - pos += bytesRead - p.write(buf.slice(0, bytesRead)) - } - p.end() - } - threw = false - } finally { - if (threw && fd) - try { fs.closeSync(fd) } catch (er) {} - } -} - -const listFile = (opt, cb) => { - const parse = new Parser(opt) - const readSize = opt.maxReadSize || 16*1024*1024 - - const file = opt.file - const p = new Promise((resolve, reject) => { - parse.on('error', reject) - parse.on('end', resolve) - - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(parse) - } - }) - }) - return cb ? p.then(cb, cb) : p -} - -const list = opt => new Parser(opt) - - -/***/ }), -/* 385 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// this[BUFFER] is the remainder of a chunk if we're waiting for -// the full 512 bytes of a header to come in. We will Buffer.concat() -// it to the next write(), which is a mem copy, but a small one. -// -// this[QUEUE] is a Yallist of entries that haven't been emitted -// yet this can only get filled up if the user keeps write()ing after -// a write() returns false, or does a write() with more than one entry -// -// We don't buffer chunks, we always parse them and either create an -// entry, or push it into the active entry. The ReadEntry class knows -// to throw data away if .ignore=true -// -// Shift entry off the buffer when it emits 'end', and emit 'entry' for -// the next one in the list. -// -// At any time, we're pushing body chunks into the entry at WRITEENTRY, -// and waiting for 'end' on the entry at READENTRY -// -// ignored entries get .resume() called on them straight away - -const warner = __webpack_require__(380) -const path = __webpack_require__(82) -const Header = __webpack_require__(378) -const EE = __webpack_require__(198) -const Yallist = __webpack_require__(369) -const maxMetaEntrySize = 1024 * 1024 -const Entry = __webpack_require__(374) -const Pax = __webpack_require__(377) -const zlib = __webpack_require__(372) - -const gzipHeader = Buffer.from([0x1f, 0x8b]) -const STATE = Symbol('state') -const WRITEENTRY = Symbol('writeEntry') -const READENTRY = Symbol('readEntry') -const NEXTENTRY = Symbol('nextEntry') -const PROCESSENTRY = Symbol('processEntry') -const EX = Symbol('extendedHeader') -const GEX = Symbol('globalExtendedHeader') -const META = Symbol('meta') -const EMITMETA = Symbol('emitMeta') -const BUFFER = Symbol('buffer') -const QUEUE = Symbol('queue') -const ENDED = Symbol('ended') -const EMITTEDEND = Symbol('emittedEnd') -const EMIT = Symbol('emit') -const UNZIP = Symbol('unzip') -const CONSUMECHUNK = Symbol('consumeChunk') -const CONSUMECHUNKSUB = Symbol('consumeChunkSub') -const CONSUMEBODY = Symbol('consumeBody') -const CONSUMEMETA = Symbol('consumeMeta') -const CONSUMEHEADER = Symbol('consumeHeader') -const CONSUMING = Symbol('consuming') -const BUFFERCONCAT = Symbol('bufferConcat') -const MAYBEEND = Symbol('maybeEnd') -const WRITING = Symbol('writing') -const ABORTED = Symbol('aborted') -const DONE = Symbol('onDone') -const SAW_VALID_ENTRY = Symbol('sawValidEntry') -const SAW_NULL_BLOCK = Symbol('sawNullBlock') -const SAW_EOF = Symbol('sawEOF') - -const noop = _ => true - -module.exports = warner(class Parser extends EE { - constructor (opt) { - opt = opt || {} - super(opt) - - this.file = opt.file || '' - - // set to boolean false when an entry starts. 1024 bytes of \0 - // is technically a valid tarball, albeit a boring one. - this[SAW_VALID_ENTRY] = null - - // these BADARCHIVE errors can't be detected early. listen on DONE. - this.on(DONE, _ => { - if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { - // either less than 1 block of data, or all entries were invalid. - // Either way, probably not even a tarball. - this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') - } - }) - - if (opt.ondone) - this.on(DONE, opt.ondone) - else - this.on(DONE, _ => { - this.emit('prefinish') - this.emit('finish') - this.emit('end') - this.emit('close') - }) - - this.strict = !!opt.strict - this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize - this.filter = typeof opt.filter === 'function' ? opt.filter : noop - - // have to set this so that streams are ok piping into it - this.writable = true - this.readable = false - - this[QUEUE] = new Yallist() - this[BUFFER] = null - this[READENTRY] = null - this[WRITEENTRY] = null - this[STATE] = 'begin' - this[META] = '' - this[EX] = null - this[GEX] = null - this[ENDED] = false - this[UNZIP] = null - this[ABORTED] = false - this[SAW_NULL_BLOCK] = false - this[SAW_EOF] = false - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - if (typeof opt.onentry === 'function') - this.on('entry', opt.onentry) - } - - [CONSUMEHEADER] (chunk, position) { - if (this[SAW_VALID_ENTRY] === null) - this[SAW_VALID_ENTRY] = false - let header - try { - header = new Header(chunk, position, this[EX], this[GEX]) - } catch (er) { - return this.warn('TAR_ENTRY_INVALID', er) - } - - if (header.nullBlock) { - if (this[SAW_NULL_BLOCK]) { - this[SAW_EOF] = true - // ending an archive with no entries. pointless, but legal. - if (this[STATE] === 'begin') - this[STATE] = 'header' - this[EMIT]('eof') - } else { - this[SAW_NULL_BLOCK] = true - this[EMIT]('nullBlock') - } - } else { - this[SAW_NULL_BLOCK] = false - if (!header.cksumValid) - this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header}) - else if (!header.path) - this.warn('TAR_ENTRY_INVALID', 'path is required', {header}) - else { - const type = header.type - if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) - this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header}) - else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) - this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header}) - else { - const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) - - // we do this for meta & ignored entries as well, because they - // are still valid tar, or else we wouldn't know to ignore them - if (!this[SAW_VALID_ENTRY]) { - if (entry.remain) { - // this might be the one! - const onend = () => { - if (!entry.invalid) - this[SAW_VALID_ENTRY] = true - } - entry.on('end', onend) - } else { - this[SAW_VALID_ENTRY] = true - } - } - - if (entry.meta) { - if (entry.size > this.maxMetaEntrySize) { - entry.ignore = true - this[EMIT]('ignoredEntry', entry) - this[STATE] = 'ignore' - entry.resume() - } else if (entry.size > 0) { - this[META] = '' - entry.on('data', c => this[META] += c) - this[STATE] = 'meta' - } - } else { - this[EX] = null - entry.ignore = entry.ignore || !this.filter(entry.path, entry) - - if (entry.ignore) { - // probably valid, just not something we care about - this[EMIT]('ignoredEntry', entry) - this[STATE] = entry.remain ? 'ignore' : 'header' - entry.resume() - } else { - if (entry.remain) - this[STATE] = 'body' - else { - this[STATE] = 'header' - entry.end() - } - - if (!this[READENTRY]) { - this[QUEUE].push(entry) - this[NEXTENTRY]() - } else - this[QUEUE].push(entry) - } - } - } - } - } - } - - [PROCESSENTRY] (entry) { - let go = true - - if (!entry) { - this[READENTRY] = null - go = false - } else if (Array.isArray(entry)) - this.emit.apply(this, entry) - else { - this[READENTRY] = entry - this.emit('entry', entry) - if (!entry.emittedEnd) { - entry.on('end', _ => this[NEXTENTRY]()) - go = false - } - } - - return go - } - - [NEXTENTRY] () { - do {} while (this[PROCESSENTRY](this[QUEUE].shift())) - - if (!this[QUEUE].length) { - // At this point, there's nothing in the queue, but we may have an - // entry which is being consumed (readEntry). - // If we don't, then we definitely can handle more data. - // If we do, and either it's flowing, or it has never had any data - // written to it, then it needs more. - // The only other possibility is that it has returned false from a - // write() call, so we wait for the next drain to continue. - const re = this[READENTRY] - const drainNow = !re || re.flowing || re.size === re.remain - if (drainNow) { - if (!this[WRITING]) - this.emit('drain') - } else - re.once('drain', _ => this.emit('drain')) - } - } - - [CONSUMEBODY] (chunk, position) { - // write up to but no more than writeEntry.blockRemain - const entry = this[WRITEENTRY] - const br = entry.blockRemain - const c = (br >= chunk.length && position === 0) ? chunk - : chunk.slice(position, position + br) - - entry.write(c) - - if (!entry.blockRemain) { - this[STATE] = 'header' - this[WRITEENTRY] = null - entry.end() - } - - return c.length - } - - [CONSUMEMETA] (chunk, position) { - const entry = this[WRITEENTRY] - const ret = this[CONSUMEBODY](chunk, position) - - // if we finished, then the entry is reset - if (!this[WRITEENTRY]) - this[EMITMETA](entry) - - return ret - } - - [EMIT] (ev, data, extra) { - if (!this[QUEUE].length && !this[READENTRY]) - this.emit(ev, data, extra) - else - this[QUEUE].push([ev, data, extra]) - } - - [EMITMETA] (entry) { - this[EMIT]('meta', this[META]) - switch (entry.type) { - case 'ExtendedHeader': - case 'OldExtendedHeader': - this[EX] = Pax.parse(this[META], this[EX], false) - break - - case 'GlobalExtendedHeader': - this[GEX] = Pax.parse(this[META], this[GEX], true) - break - - case 'NextFileHasLongPath': - case 'OldGnuLongPath': - this[EX] = this[EX] || Object.create(null) - this[EX].path = this[META].replace(/\0.*/, '') - break - - case 'NextFileHasLongLinkpath': - this[EX] = this[EX] || Object.create(null) - this[EX].linkpath = this[META].replace(/\0.*/, '') - break - - /* istanbul ignore next */ - default: throw new Error('unknown meta: ' + entry.type) - } - } - - abort (error) { - this[ABORTED] = true - this.emit('abort', error) - // always throws, even in non-strict mode - this.warn('TAR_ABORT', error, { recoverable: false }) - } - - write (chunk) { - if (this[ABORTED]) - return - - // first write, might be gzipped - if (this[UNZIP] === null && chunk) { - if (this[BUFFER]) { - chunk = Buffer.concat([this[BUFFER], chunk]) - this[BUFFER] = null - } - if (chunk.length < gzipHeader.length) { - this[BUFFER] = chunk - return true - } - for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { - if (chunk[i] !== gzipHeader[i]) - this[UNZIP] = false - } - if (this[UNZIP] === null) { - const ended = this[ENDED] - this[ENDED] = false - this[UNZIP] = new zlib.Unzip() - this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) - this[UNZIP].on('error', er => this.abort(er)) - this[UNZIP].on('end', _ => { - this[ENDED] = true - this[CONSUMECHUNK]() - }) - this[WRITING] = true - const ret = this[UNZIP][ended ? 'end' : 'write' ](chunk) - this[WRITING] = false - return ret - } - } - - this[WRITING] = true - if (this[UNZIP]) - this[UNZIP].write(chunk) - else - this[CONSUMECHUNK](chunk) - this[WRITING] = false - - // return false if there's a queue, or if the current entry isn't flowing - const ret = - this[QUEUE].length ? false : - this[READENTRY] ? this[READENTRY].flowing : - true - - // if we have no queue, then that means a clogged READENTRY - if (!ret && !this[QUEUE].length) - this[READENTRY].once('drain', _ => this.emit('drain')) - - return ret - } - - [BUFFERCONCAT] (c) { - if (c && !this[ABORTED]) - this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c - } - - [MAYBEEND] () { - if (this[ENDED] && - !this[EMITTEDEND] && - !this[ABORTED] && - !this[CONSUMING]) { - this[EMITTEDEND] = true - const entry = this[WRITEENTRY] - if (entry && entry.blockRemain) { - // truncated, likely a damaged file - const have = this[BUFFER] ? this[BUFFER].length : 0 - this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ - entry.blockRemain} more bytes, only ${have} available)`, {entry}) - if (this[BUFFER]) - entry.write(this[BUFFER]) - entry.end() - } - this[EMIT](DONE) - } - } - - [CONSUMECHUNK] (chunk) { - if (this[CONSUMING]) - this[BUFFERCONCAT](chunk) - else if (!chunk && !this[BUFFER]) - this[MAYBEEND]() - else { - this[CONSUMING] = true - if (this[BUFFER]) { - this[BUFFERCONCAT](chunk) - const c = this[BUFFER] - this[BUFFER] = null - this[CONSUMECHUNKSUB](c) - } else { - this[CONSUMECHUNKSUB](chunk) - } - - while (this[BUFFER] && - this[BUFFER].length >= 512 && - !this[ABORTED] && - !this[SAW_EOF]) { - const c = this[BUFFER] - this[BUFFER] = null - this[CONSUMECHUNKSUB](c) - } - this[CONSUMING] = false - } - - if (!this[BUFFER] || this[ENDED]) - this[MAYBEEND]() - } - - [CONSUMECHUNKSUB] (chunk) { - // we know that we are in CONSUMING mode, so anything written goes into - // the buffer. Advance the position and put any remainder in the buffer. - let position = 0 - let length = chunk.length - while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { - switch (this[STATE]) { - case 'begin': - case 'header': - this[CONSUMEHEADER](chunk, position) - position += 512 - break - - case 'ignore': - case 'body': - position += this[CONSUMEBODY](chunk, position) - break - - case 'meta': - position += this[CONSUMEMETA](chunk, position) - break - - /* istanbul ignore next */ - default: - throw new Error('invalid state: ' + this[STATE]) - } - } - - if (position < length) { - if (this[BUFFER]) - this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) - else - this[BUFFER] = chunk.slice(position) - } - } - - end (chunk) { - if (!this[ABORTED]) { - if (this[UNZIP]) - this[UNZIP].end(chunk) - else { - this[ENDED] = true - this.write(chunk) - } - } - } -}) - - -/***/ }), -/* 386 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// tar -r -const hlo = __webpack_require__(366) -const Pack = __webpack_require__(367) -const Parse = __webpack_require__(385) -const fs = __webpack_require__(66) -const fsm = __webpack_require__(383) -const t = __webpack_require__(384) -const path = __webpack_require__(82) - -// starting at the head of the file, read a Header -// If the checksum is invalid, that's our position to start writing -// If it is, jump forward by the specified size (round up to 512) -// and try again. -// Write the new Pack stream starting there. - -const Header = __webpack_require__(378) - -const r = module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) - - if (!opt.file) - throw new TypeError('file is required') - - if (opt.gzip) - throw new TypeError('cannot append to compressed archives') - - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') - - files = Array.from(files) - - return opt.sync ? replaceSync(opt, files) - : replace(opt, files, cb) -} - -const replaceSync = (opt, files) => { - const p = new Pack.Sync(opt) - - let threw = true - let fd - let position - - try { - try { - fd = fs.openSync(opt.file, 'r+') - } catch (er) { - if (er.code === 'ENOENT') - fd = fs.openSync(opt.file, 'w+') - else - throw er - } - - const st = fs.fstatSync(fd) - const headBuf = Buffer.alloc(512) - - POSITION: for (position = 0; position < st.size; position += 512) { - for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { - bytes = fs.readSync( - fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos - ) - - if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) - throw new Error('cannot append to compressed archives') - - if (!bytes) - break POSITION - } - - let h = new Header(headBuf) - if (!h.cksumValid) - break - let entryBlockSize = 512 * Math.ceil(h.size / 512) - if (position + entryBlockSize + 512 > st.size) - break - // the 512 for the header we just parsed will be added as well - // also jump ahead all the blocks for the body - position += entryBlockSize - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime) - } - threw = false - - streamSync(opt, p, position, fd, files) - } finally { - if (threw) - try { fs.closeSync(fd) } catch (er) {} - } -} - -const streamSync = (opt, p, position, fd, files) => { - const stream = new fsm.WriteStreamSync(opt.file, { - fd: fd, - start: position - }) - p.pipe(stream) - addFilesSync(p, files) -} - -const replace = (opt, files, cb) => { - files = Array.from(files) - const p = new Pack(opt) - - const getPos = (fd, size, cb_) => { - const cb = (er, pos) => { - if (er) - fs.close(fd, _ => cb_(er)) - else - cb_(null, pos) - } - - let position = 0 - if (size === 0) - return cb(null, 0) - - let bufPos = 0 - const headBuf = Buffer.alloc(512) - const onread = (er, bytes) => { - if (er) - return cb(er) - bufPos += bytes - if (bufPos < 512 && bytes) - return fs.read( - fd, headBuf, bufPos, headBuf.length - bufPos, - position + bufPos, onread - ) - - if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) - return cb(new Error('cannot append to compressed archives')) - - // truncated header - if (bufPos < 512) - return cb(null, position) - - const h = new Header(headBuf) - if (!h.cksumValid) - return cb(null, position) - - const entryBlockSize = 512 * Math.ceil(h.size / 512) - if (position + entryBlockSize + 512 > size) - return cb(null, position) - - position += entryBlockSize + 512 - if (position >= size) - return cb(null, position) - - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime) - bufPos = 0 - fs.read(fd, headBuf, 0, 512, position, onread) - } - fs.read(fd, headBuf, 0, 512, position, onread) - } - - const promise = new Promise((resolve, reject) => { - p.on('error', reject) - let flag = 'r+' - const onopen = (er, fd) => { - if (er && er.code === 'ENOENT' && flag === 'r+') { - flag = 'w+' - return fs.open(opt.file, flag, onopen) - } - - if (er) - return reject(er) - - fs.fstat(fd, (er, st) => { - if (er) - return reject(er) - getPos(fd, st.size, (er, position) => { - if (er) - return reject(er) - const stream = new fsm.WriteStream(opt.file, { - fd: fd, - start: position - }) - p.pipe(stream) - stream.on('error', reject) - stream.on('close', resolve) - addFilesAsync(p, files) - }) - }) - } - fs.open(opt.file, flag, onopen) - }) - - return cb ? promise.then(cb, cb) : promise -} - -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') - t({ - file: path.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry) - }) - else - p.add(file) - }) - p.end() -} - -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') - return t({ - file: path.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: entry => p.add(entry) - }).then(_ => addFilesAsync(p, files)) - else - p.add(file) - } - p.end() -} - - -/***/ }), -/* 387 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// tar -u - -const hlo = __webpack_require__(366) -const r = __webpack_require__(386) -// just call tar.r with the filter and mtimeCache - -const u = module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) - - if (!opt.file) - throw new TypeError('file is required') - - if (opt.gzip) - throw new TypeError('cannot append to compressed archives') - - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') - - files = Array.from(files) - - mtimeFilter(opt) - return r(opt, files, cb) -} - -const mtimeFilter = opt => { - const filter = opt.filter - - if (!opt.mtimeCache) - opt.mtimeCache = new Map() - - opt.filter = filter ? (path, stat) => - filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) - : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) -} - - -/***/ }), -/* 388 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// tar -x -const hlo = __webpack_require__(366) -const Unpack = __webpack_require__(389) -const fs = __webpack_require__(66) -const fsm = __webpack_require__(383) -const path = __webpack_require__(82) - -const x = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} - - if (typeof files === 'function') - cb = files, files = null - - if (!files) - files = [] - else - files = Array.from(files) - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') - - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') - - if (files.length) - filesFilter(opt, files) - - return opt.file && opt.sync ? extractFileSync(opt) - : opt.file ? extractFile(opt, cb) - : opt.sync ? extractSync(opt) - : extract(opt) -} - -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter - - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) - - map.set(file, ret) - return ret - } - - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) -} - -const extractFileSync = opt => { - const u = new Unpack.Sync(opt) - - const file = opt.file - let threw = true - let fd - const stat = fs.statSync(file) - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - const readSize = opt.maxReadSize || 16*1024*1024 - const stream = new fsm.ReadStreamSync(file, { - readSize: readSize, - size: stat.size - }) - stream.pipe(u) -} - -const extractFile = (opt, cb) => { - const u = new Unpack(opt) - const readSize = opt.maxReadSize || 16*1024*1024 - - const file = opt.file - const p = new Promise((resolve, reject) => { - u.on('error', reject) - u.on('close', resolve) - - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(u) - } - }) - }) - return cb ? p.then(cb, cb) : p -} - -const extractSync = opt => { - return new Unpack.Sync(opt) -} - -const extract = opt => { - return new Unpack(opt) -} - - -/***/ }), -/* 389 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. -// but the path reservations are required to avoid race conditions where -// parallelized unpack ops may mess with one another, due to dependencies -// (like a Link depending on its target) or destructive operations (like -// clobbering an fs object to create one of a different type.) - -const assert = __webpack_require__(108) -const EE = __webpack_require__(198).EventEmitter -const Parser = __webpack_require__(385) -const fs = __webpack_require__(66) -const fsm = __webpack_require__(383) -const path = __webpack_require__(82) -const mkdir = __webpack_require__(390) -const mkdirSync = mkdir.sync -const wc = __webpack_require__(381) -const pathReservations = __webpack_require__(392) - -const ONENTRY = Symbol('onEntry') -const CHECKFS = Symbol('checkFs') -const CHECKFS2 = Symbol('checkFs2') -const ISREUSABLE = Symbol('isReusable') -const MAKEFS = Symbol('makeFs') -const FILE = Symbol('file') -const DIRECTORY = Symbol('directory') -const LINK = Symbol('link') -const SYMLINK = Symbol('symlink') -const HARDLINK = Symbol('hardlink') -const UNSUPPORTED = Symbol('unsupported') -const UNKNOWN = Symbol('unknown') -const CHECKPATH = Symbol('checkPath') -const MKDIR = Symbol('mkdir') -const ONERROR = Symbol('onError') -const PENDING = Symbol('pending') -const PEND = Symbol('pend') -const UNPEND = Symbol('unpend') -const ENDED = Symbol('ended') -const MAYBECLOSE = Symbol('maybeClose') -const SKIP = Symbol('skip') -const DOCHOWN = Symbol('doChown') -const UID = Symbol('uid') -const GID = Symbol('gid') -const crypto = __webpack_require__(221) -const getFlag = __webpack_require__(393) - -/* istanbul ignore next */ -const neverCalled = () => { - throw new Error('sync function called cb somehow?!?') -} - -// Unlinks on Windows are not atomic. -// -// This means that if you have a file entry, followed by another -// file entry with an identical name, and you cannot re-use the file -// (because it's a hardlink, or because unlink:true is set, or it's -// Windows, which does not have useful nlink values), then the unlink -// will be committed to the disk AFTER the new file has been written -// over the old one, deleting the new file. -// -// To work around this, on Windows systems, we rename the file and then -// delete the renamed file. It's a sloppy kludge, but frankly, I do not -// know of a better way to do this, given windows' non-atomic unlink -// semantics. -// -// See: https://github.com/npm/node-tar/issues/183 -/* istanbul ignore next */ -const unlinkFile = (path, cb) => { - if (process.platform !== 'win32') - return fs.unlink(path, cb) - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.rename(path, name, er => { - if (er) - return cb(er) - fs.unlink(name, cb) - }) -} - -/* istanbul ignore next */ -const unlinkFileSync = path => { - if (process.platform !== 'win32') - return fs.unlinkSync(path) - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.renameSync(path, name) - fs.unlinkSync(name) -} - -// this.gid, entry.gid, this.processUid -const uint32 = (a, b, c) => - a === a >>> 0 ? a - : b === b >>> 0 ? b - : c - -class Unpack extends Parser { - constructor (opt) { - if (!opt) - opt = {} - - opt.ondone = _ => { - this[ENDED] = true - this[MAYBECLOSE]() - } - - super(opt) - - this.reservations = pathReservations() - - this.transform = typeof opt.transform === 'function' ? opt.transform : null - - this.writable = true - this.readable = false - - this[PENDING] = 0 - this[ENDED] = false - - this.dirCache = opt.dirCache || new Map() - - if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { - // need both or neither - if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') - throw new TypeError('cannot set owner without number uid and gid') - if (opt.preserveOwner) - throw new TypeError( - 'cannot preserve owner in archive and also set owner explicitly') - this.uid = opt.uid - this.gid = opt.gid - this.setOwner = true - } else { - this.uid = null - this.gid = null - this.setOwner = false - } - - // default true for root - if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') - this.preserveOwner = process.getuid && process.getuid() === 0 - else - this.preserveOwner = !!opt.preserveOwner - - this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? - process.getuid() : null - this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? - process.getgid() : null - - // mostly just for testing, but useful in some cases. - // Forcibly trigger a chown on every entry, no matter what - this.forceChown = opt.forceChown === true - - // turn > this[ONENTRY](entry)) - } - - // a bad or damaged archive is a warning for Parser, but an error - // when extracting. Mark those errors as unrecoverable, because - // the Unpack contract cannot be met. - warn (code, msg, data = {}) { - if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') - data.recoverable = false - return super.warn(code, msg, data) - } - - [MAYBECLOSE] () { - if (this[ENDED] && this[PENDING] === 0) { - this.emit('prefinish') - this.emit('finish') - this.emit('end') - this.emit('close') - } - } - - [CHECKPATH] (entry) { - if (this.strip) { - const parts = entry.path.split(/\/|\\/) - if (parts.length < this.strip) - return false - entry.path = parts.slice(this.strip).join('/') - - if (entry.type === 'Link') { - const linkparts = entry.linkpath.split(/\/|\\/) - if (linkparts.length >= this.strip) - entry.linkpath = linkparts.slice(this.strip).join('/') - } - } - - if (!this.preservePaths) { - const p = entry.path - if (p.match(/(^|\/|\\)\.\.(\\|\/|$)/)) { - this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { - entry, - path: p, - }) - return false - } - - // absolutes on posix are also absolutes on win32 - // so we only need to test this one to get both - if (path.win32.isAbsolute(p)) { - const parsed = path.win32.parse(p) - entry.path = p.substr(parsed.root.length) - const r = parsed.root - this.warn('TAR_ENTRY_INFO', `stripping ${r} from absolute path`, { - entry, - path: p, - }) - } - } - - // only encode : chars that aren't drive letter indicators - if (this.win32) { - const parsed = path.win32.parse(entry.path) - entry.path = parsed.root === '' ? wc.encode(entry.path) - : parsed.root + wc.encode(entry.path.substr(parsed.root.length)) - } - - if (path.isAbsolute(entry.path)) - entry.absolute = entry.path - else - entry.absolute = path.resolve(this.cwd, entry.path) - - return true - } - - [ONENTRY] (entry) { - if (!this[CHECKPATH](entry)) - return entry.resume() - - assert.equal(typeof entry.absolute, 'string') - - switch (entry.type) { - case 'Directory': - case 'GNUDumpDir': - if (entry.mode) - entry.mode = entry.mode | 0o700 - - case 'File': - case 'OldFile': - case 'ContiguousFile': - case 'Link': - case 'SymbolicLink': - return this[CHECKFS](entry) - - case 'CharacterDevice': - case 'BlockDevice': - case 'FIFO': - return this[UNSUPPORTED](entry) - } - } - - [ONERROR] (er, entry) { - // Cwd has to exist, or else nothing works. That's serious. - // Other errors are warnings, which raise the error in strict - // mode, but otherwise continue on. - if (er.name === 'CwdError') - this.emit('error', er) - else { - this.warn('TAR_ENTRY_ERROR', er, {entry}) - this[UNPEND]() - entry.resume() - } - } - - [MKDIR] (dir, mode, cb) { - mkdir(dir, { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode: mode - }, cb) - } - - [DOCHOWN] (entry) { - // in preserve owner mode, chown if the entry doesn't match process - // in set owner mode, chown if setting doesn't match process - return this.forceChown || - this.preserveOwner && - ( typeof entry.uid === 'number' && entry.uid !== this.processUid || - typeof entry.gid === 'number' && entry.gid !== this.processGid ) - || - ( typeof this.uid === 'number' && this.uid !== this.processUid || - typeof this.gid === 'number' && this.gid !== this.processGid ) - } - - [UID] (entry) { - return uint32(this.uid, entry.uid, this.processUid) - } - - [GID] (entry) { - return uint32(this.gid, entry.gid, this.processGid) - } - - [FILE] (entry, fullyDone) { - const mode = entry.mode & 0o7777 || this.fmode - const stream = new fsm.WriteStream(entry.absolute, { - flags: getFlag(entry.size), - mode: mode, - autoClose: false - }) - stream.on('error', er => this[ONERROR](er, entry)) - - let actions = 1 - const done = er => { - if (er) - return this[ONERROR](er, entry) - - if (--actions === 0) { - fs.close(stream.fd, er => { - fullyDone() - er ? this[ONERROR](er, entry) : this[UNPEND]() - }) - } - } - - stream.on('finish', _ => { - // if futimes fails, try utimes - // if utimes fails, fail with the original error - // same for fchown/chown - const abs = entry.absolute - const fd = stream.fd - - if (entry.mtime && !this.noMtime) { - actions++ - const atime = entry.atime || new Date() - const mtime = entry.mtime - fs.futimes(fd, atime, mtime, er => - er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) - : done()) - } - - if (this[DOCHOWN](entry)) { - actions++ - const uid = this[UID](entry) - const gid = this[GID](entry) - fs.fchown(fd, uid, gid, er => - er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) - : done()) - } - - done() - }) - - const tx = this.transform ? this.transform(entry) || entry : entry - if (tx !== entry) { - tx.on('error', er => this[ONERROR](er, entry)) - entry.pipe(tx) - } - tx.pipe(stream) - } - - [DIRECTORY] (entry, fullyDone) { - const mode = entry.mode & 0o7777 || this.dmode - this[MKDIR](entry.absolute, mode, er => { - if (er) { - fullyDone() - return this[ONERROR](er, entry) - } - - let actions = 1 - const done = _ => { - if (--actions === 0) { - fullyDone() - this[UNPEND]() - entry.resume() - } - } - - if (entry.mtime && !this.noMtime) { - actions++ - fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) - } - - if (this[DOCHOWN](entry)) { - actions++ - fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) - } - - done() - }) - } - - [UNSUPPORTED] (entry) { - entry.unsupported = true - this.warn('TAR_ENTRY_UNSUPPORTED', - `unsupported entry type: ${entry.type}`, {entry}) - entry.resume() - } - - [SYMLINK] (entry, done) { - this[LINK](entry, entry.linkpath, 'symlink', done) - } - - [HARDLINK] (entry, done) { - this[LINK](entry, path.resolve(this.cwd, entry.linkpath), 'link', done) - } - - [PEND] () { - this[PENDING]++ - } - - [UNPEND] () { - this[PENDING]-- - this[MAYBECLOSE]() - } - - [SKIP] (entry) { - this[UNPEND]() - entry.resume() - } - - // Check if we can reuse an existing filesystem entry safely and - // overwrite it, rather than unlinking and recreating - // Windows doesn't report a useful nlink, so we just never reuse entries - [ISREUSABLE] (entry, st) { - return entry.type === 'File' && - !this.unlink && - st.isFile() && - st.nlink <= 1 && - process.platform !== 'win32' - } - - // check if a thing is there, and if so, try to clobber it - [CHECKFS] (entry) { - this[PEND]() - const paths = [entry.path] - if (entry.linkpath) - paths.push(entry.linkpath) - this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) - } - [CHECKFS2] (entry, done) { - this[MKDIR](path.dirname(entry.absolute), this.dmode, er => { - if (er) { - done() - return this[ONERROR](er, entry) - } - fs.lstat(entry.absolute, (er, st) => { - if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { - this[SKIP](entry) - done() - } else if (er || this[ISREUSABLE](entry, st)) { - this[MAKEFS](null, entry, done) - } - else if (st.isDirectory()) { - if (entry.type === 'Directory') { - if (!entry.mode || (st.mode & 0o7777) === entry.mode) - this[MAKEFS](null, entry, done) - else - fs.chmod(entry.absolute, entry.mode, - er => this[MAKEFS](er, entry, done)) - } else - fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) - } else - unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) - }) - }) - } - - [MAKEFS] (er, entry, done) { - if (er) - return this[ONERROR](er, entry) - - switch (entry.type) { - case 'File': - case 'OldFile': - case 'ContiguousFile': - return this[FILE](entry, done) - - case 'Link': - return this[HARDLINK](entry, done) - - case 'SymbolicLink': - return this[SYMLINK](entry, done) - - case 'Directory': - case 'GNUDumpDir': - return this[DIRECTORY](entry, done) - } - } - - [LINK] (entry, linkpath, link, done) { - // XXX: get the type ('file' or 'dir') for windows - fs[link](linkpath, entry.absolute, er => { - if (er) - return this[ONERROR](er, entry) - done() - this[UNPEND]() - entry.resume() - }) - } -} - -class UnpackSync extends Unpack { - constructor (opt) { - super(opt) - } - - [CHECKFS] (entry) { - const er = this[MKDIR](path.dirname(entry.absolute), this.dmode, neverCalled) - if (er) - return this[ONERROR](er, entry) - try { - const st = fs.lstatSync(entry.absolute) - if (this.keep || this.newer && st.mtime > entry.mtime) - return this[SKIP](entry) - else if (this[ISREUSABLE](entry, st)) - return this[MAKEFS](null, entry, neverCalled) - else { - try { - if (st.isDirectory()) { - if (entry.type === 'Directory') { - if (entry.mode && (st.mode & 0o7777) !== entry.mode) - fs.chmodSync(entry.absolute, entry.mode) - } else - fs.rmdirSync(entry.absolute) - } else - unlinkFileSync(entry.absolute) - return this[MAKEFS](null, entry, neverCalled) - } catch (er) { - return this[ONERROR](er, entry) - } - } - } catch (er) { - return this[MAKEFS](null, entry, neverCalled) - } - } - - [FILE] (entry, _) { - const mode = entry.mode & 0o7777 || this.fmode - - const oner = er => { - let closeError - try { - fs.closeSync(fd) - } catch (e) { - closeError = e - } - if (er || closeError) - this[ONERROR](er || closeError, entry) - } - - let stream - let fd - try { - fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) - } catch (er) { - return oner(er) - } - const tx = this.transform ? this.transform(entry) || entry : entry - if (tx !== entry) { - tx.on('error', er => this[ONERROR](er, entry)) - entry.pipe(tx) - } - - tx.on('data', chunk => { - try { - fs.writeSync(fd, chunk, 0, chunk.length) - } catch (er) { - oner(er) - } - }) - - tx.on('end', _ => { - let er = null - // try both, falling futimes back to utimes - // if either fails, handle the first error - if (entry.mtime && !this.noMtime) { - const atime = entry.atime || new Date() - const mtime = entry.mtime - try { - fs.futimesSync(fd, atime, mtime) - } catch (futimeser) { - try { - fs.utimesSync(entry.absolute, atime, mtime) - } catch (utimeser) { - er = futimeser - } - } - } - - if (this[DOCHOWN](entry)) { - const uid = this[UID](entry) - const gid = this[GID](entry) - - try { - fs.fchownSync(fd, uid, gid) - } catch (fchowner) { - try { - fs.chownSync(entry.absolute, uid, gid) - } catch (chowner) { - er = er || fchowner - } - } - } - - oner(er) - }) - } - - [DIRECTORY] (entry, _) { - const mode = entry.mode & 0o7777 || this.dmode - const er = this[MKDIR](entry.absolute, mode) - if (er) - return this[ONERROR](er, entry) - if (entry.mtime && !this.noMtime) { - try { - fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) - } catch (er) {} - } - if (this[DOCHOWN](entry)) { - try { - fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) - } catch (er) {} - } - entry.resume() - } - - [MKDIR] (dir, mode) { - try { - return mkdir.sync(dir, { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode: mode - }) - } catch (er) { - return er - } - } - - [LINK] (entry, linkpath, link, _) { - try { - fs[link + 'Sync'](linkpath, entry.absolute) - entry.resume() - } catch (er) { - return this[ONERROR](er, entry) - } - } -} - -Unpack.Sync = UnpackSync -module.exports = Unpack - - -/***/ }), -/* 390 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// wrapper around mkdirp for tar's needs. - -// TODO: This should probably be a class, not functionally -// passing around state in a gazillion args. - -const mkdirp = __webpack_require__(272) -const fs = __webpack_require__(66) -const path = __webpack_require__(82) -const chownr = __webpack_require__(391) - -class SymlinkError extends Error { - constructor (symlink, path) { - super('Cannot extract through symbolic link') - this.path = path - this.symlink = symlink - } - - get name () { - return 'SylinkError' - } -} - -class CwdError extends Error { - constructor (path, code) { - super(code + ': Cannot cd into \'' + path + '\'') - this.path = path - this.code = code - } - - get name () { - return 'CwdError' - } -} - -const mkdir = module.exports = (dir, opt, cb) => { - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - const mode = opt.mode | 0o0700 - const needChmod = (mode & umask) !== 0 - - const uid = opt.uid - const gid = opt.gid - const doChown = typeof uid === 'number' && - typeof gid === 'number' && - ( uid !== opt.processUid || gid !== opt.processGid ) - - const preserve = opt.preserve - const unlink = opt.unlink - const cache = opt.cache - const cwd = opt.cwd - - const done = (er, created) => { - if (er) - cb(er) - else { - cache.set(dir, true) - if (created && doChown) - chownr(created, uid, gid, er => done(er)) - else if (needChmod) - fs.chmod(dir, mode, cb) - else - cb() - } - } - - if (cache && cache.get(dir) === true) - return done() - - if (dir === cwd) - return fs.stat(dir, (er, st) => { - if (er || !st.isDirectory()) - er = new CwdError(dir, er && er.code || 'ENOTDIR') - done(er) - }) - - if (preserve) - return mkdirp(dir, {mode}).then(made => done(null, made), done) - - const sub = path.relative(cwd, dir) - const parts = sub.split(/\/|\\/) - mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) -} - -const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { - if (!parts.length) - return cb(null, created) - const p = parts.shift() - const part = base + '/' + p - if (cache.get(part)) - return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) -} - -const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { - if (er) { - if (er.path && path.dirname(er.path) === cwd && - (er.code === 'ENOTDIR' || er.code === 'ENOENT')) - return cb(new CwdError(cwd, er.code)) - - fs.lstat(part, (statEr, st) => { - if (statEr) - cb(statEr) - else if (st.isDirectory()) - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - else if (unlink) - fs.unlink(part, er => { - if (er) - return cb(er) - fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) - }) - else if (st.isSymbolicLink()) - return cb(new SymlinkError(part, part + '/' + parts.join('/'))) - else - cb(er) - }) - } else { - created = created || part - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - } -} - -const mkdirSync = module.exports.sync = (dir, opt) => { - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - const mode = opt.mode | 0o0700 - const needChmod = (mode & umask) !== 0 - - const uid = opt.uid - const gid = opt.gid - const doChown = typeof uid === 'number' && - typeof gid === 'number' && - ( uid !== opt.processUid || gid !== opt.processGid ) - - const preserve = opt.preserve - const unlink = opt.unlink - const cache = opt.cache - const cwd = opt.cwd - - const done = (created) => { - cache.set(dir, true) - if (created && doChown) - chownr.sync(created, uid, gid) - if (needChmod) - fs.chmodSync(dir, mode) - } - - if (cache && cache.get(dir) === true) - return done() - - if (dir === cwd) { - let ok = false - let code = 'ENOTDIR' - try { - ok = fs.statSync(dir).isDirectory() - } catch (er) { - code = er.code - } finally { - if (!ok) - throw new CwdError(dir, code) - } - done() - return - } - - if (preserve) - return done(mkdirp.sync(dir, mode)) - - const sub = path.relative(cwd, dir) - const parts = sub.split(/\/|\\/) - let created = null - for (let p = parts.shift(), part = cwd; - p && (part += '/' + p); - p = parts.shift()) { - - if (cache.get(part)) - continue - - try { - fs.mkdirSync(part, mode) - created = created || part - cache.set(part, true) - } catch (er) { - if (er.path && path.dirname(er.path) === cwd && - (er.code === 'ENOTDIR' || er.code === 'ENOENT')) - return new CwdError(cwd, er.code) - - const st = fs.lstatSync(part) - if (st.isDirectory()) { - cache.set(part, true) - continue - } else if (unlink) { - fs.unlinkSync(part) - fs.mkdirSync(part, mode) - created = created || part - cache.set(part, true) - continue - } else if (st.isSymbolicLink()) - return new SymlinkError(part, part + '/' + parts.join('/')) - } - } - - return done(created) -} - - -/***/ }), -/* 391 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const fs = __webpack_require__(66) -const path = __webpack_require__(82) - -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' - -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) - -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} - -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} - -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb - -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) - -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) - -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) -} - -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) - - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) - } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - } -} - - -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) - - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } - - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) -} - -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er - } - } - - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) - - handleEISDirSync(path.resolve(p, child.name), uid, gid) -} - -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er - } - - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) - - return handleEISDirSync(p, uid, gid) -} - -module.exports = chownr -chownr.sync = chownrSync - - -/***/ }), -/* 392 */ -/***/ (function(module, exports, __webpack_require__) { - -// A path exclusive reservation system -// reserve([list, of, paths], fn) -// When the fn is first in line for all its paths, it -// is called with a cb that clears the reservation. -// -// Used by async unpack to avoid clobbering paths in use, -// while still allowing maximal safe parallelization. - -const assert = __webpack_require__(108) - -module.exports = () => { - // path => [function or Set] - // A Set object means a directory reservation - // A fn is a direct reservation on that path - const queues = new Map() - - // fn => {paths:[path,...], dirs:[path, ...]} - const reservations = new Map() - - // return a set of parent dirs for a given path - const { join } = __webpack_require__(82) - const getDirs = path => - join(path).split(/[\\\/]/).slice(0, -1).reduce((set, path) => - set.length ? set.concat(join(set[set.length-1], path)) : [path], []) - - // functions currently running - const running = new Set() - - // return the queues for each path the function cares about - // fn => {paths, dirs} - const getQueues = fn => { - const res = reservations.get(fn) - /* istanbul ignore if - unpossible */ - if (!res) - throw new Error('function does not have any path reservations') - return { - paths: res.paths.map(path => queues.get(path)), - dirs: [...res.dirs].map(path => queues.get(path)), - } - } - - // check if fn is first in line for all its paths, and is - // included in the first set for all its dir queues - const check = fn => { - const {paths, dirs} = getQueues(fn) - return paths.every(q => q[0] === fn) && - dirs.every(q => q[0] instanceof Set && q[0].has(fn)) - } - - // run the function if it's first in line and not already running - const run = fn => { - if (running.has(fn) || !check(fn)) - return false - running.add(fn) - fn(() => clear(fn)) - return true - } - - const clear = fn => { - if (!running.has(fn)) - return false - - const { paths, dirs } = reservations.get(fn) - const next = new Set() - - paths.forEach(path => { - const q = queues.get(path) - assert.equal(q[0], fn) - if (q.length === 1) - queues.delete(path) - else { - q.shift() - if (typeof q[0] === 'function') - next.add(q[0]) - else - q[0].forEach(fn => next.add(fn)) - } - }) - - dirs.forEach(dir => { - const q = queues.get(dir) - assert(q[0] instanceof Set) - if (q[0].size === 1 && q.length === 1) { - queues.delete(dir) - } else if (q[0].size === 1) { - q.shift() - - // must be a function or else the Set would've been reused - next.add(q[0]) - } else - q[0].delete(fn) - }) - running.delete(fn) - - next.forEach(fn => run(fn)) - return true - } - - const reserve = (paths, fn) => { - const dirs = new Set( - paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) - ) - reservations.set(fn, {dirs, paths}) - paths.forEach(path => { - const q = queues.get(path) - if (!q) - queues.set(path, [fn]) - else - q.push(fn) - }) - dirs.forEach(dir => { - const q = queues.get(dir) - if (!q) - queues.set(dir, [new Set([fn])]) - else if (q[q.length-1] instanceof Set) - q[q.length-1].add(fn) - else - q.push(new Set([fn])) - }) - - return run(fn) - } - - return { check, reserve } -} - - -/***/ }), -/* 393 */ -/***/ (function(module, exports, __webpack_require__) { - -// Get the appropriate flag to use for creating files -// We use fmap on Windows platforms for files less than -// 512kb. This is a fairly low limit, but avoids making -// things slower in some cases. Since most of what this -// library is used for is extracting tarballs of many -// relatively small files in npm packages and the like, -// it can be a big boost on Windows platforms. -// Only supported in Node v12.9.0 and above. -const platform = process.env.__FAKE_PLATFORM__ || process.platform -const isWindows = platform === 'win32' -const fs = global.__FAKE_TESTING_FS__ || __webpack_require__(66) - -/* istanbul ignore next */ -const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants - -const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP -const fMapLimit = 512 * 1024 -const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY -module.exports = !fMapEnabled ? () => 'w' - : size => size < fMapLimit ? fMapFlag : 'w' - - -/***/ }), -/* 394 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Polyfills for node 0.8 -__webpack_require__(395); -__webpack_require__(396); -__webpack_require__(398); - - -exports.Parse = __webpack_require__(399); -exports.ParseOne = __webpack_require__(461); -exports.Extract = __webpack_require__(463); -exports.Open = __webpack_require__(481); - -/***/ }), -/* 395 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var listenerCount = __webpack_require__(198).listenerCount -// listenerCount isn't in node 0.10, so here's a basic polyfill -listenerCount = listenerCount || function (ee, event) { - var listeners = ee && ee._events && ee._events[event] - if (Array.isArray(listeners)) { - return listeners.length - } else if (typeof listeners === 'function') { - return 1 - } else { - return 0 - } -} - -module.exports = listenerCount - - -/***/ }), -/* 396 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var initBuffer = __webpack_require__(397); - -if (!Buffer.prototype.indexOf) { - Buffer.prototype.indexOf = function (value, offset) { - offset = offset || 0; - - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } - - var len = value.length; - - for (var i = offset; i <= this.length - len; i++) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } - - if (!mismatch) { - return i; - } - } - - return -1; - }; -} - -function bufferLastIndexOf (value, offset) { - - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } - - var len = value.length; - offset = offset || this.length - len; - - for (var i = offset; i >= 0; i--) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } - - if (!mismatch) { - return i; - } - } - - return -1; -} - - -if (Buffer.prototype.lastIndexOf) { - // check Buffer#lastIndexOf is usable: https://github.com/nodejs/node/issues/4604 - if (initBuffer("ABC").lastIndexOf ("ABC") === -1) - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} else { - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} - - -/***/ }), -/* 397 */ -/***/ (function(module, exports) { - -module.exports = function initBuffer(val) { - // assume old version - var nodeVersion = process && process.version ? process.version : "v5.0.0"; - var major = nodeVersion.split(".")[0].replace("v", ""); - return major < 6 - ? new Buffer(val) - : Buffer.from(val); -}; - -/***/ }), -/* 398 */ -/***/ (function(module, exports) { - -(function (global, undefined) { - "use strict"; - - if (global.setImmediate) { - return; - } - - var nextHandle = 1; // Spec says greater than zero - var tasksByHandle = {}; - var currentlyRunningATask = false; - var doc = global.document; - var registerImmediate; - - function setImmediate(callback) { - // Callback can either be a function or a string - if (typeof callback !== "function") { - callback = new Function("" + callback); - } - // Copy function arguments - var args = new Array(arguments.length - 1); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 1]; - } - // Store and register the task - var task = { callback: callback, args: args }; - tasksByHandle[nextHandle] = task; - registerImmediate(nextHandle); - return nextHandle++; - } - - function clearImmediate(handle) { - delete tasksByHandle[handle]; - } - - function run(task) { - var callback = task.callback; - var args = task.args; - switch (args.length) { - case 0: - callback(); - break; - case 1: - callback(args[0]); - break; - case 2: - callback(args[0], args[1]); - break; - case 3: - callback(args[0], args[1], args[2]); - break; - default: - callback.apply(undefined, args); - break; - } - } - - function runIfPresent(handle) { - // From the spec: "Wait until any invocations of this algorithm started before this one have completed." - // So if we're currently running a task, we'll need to delay this invocation. - if (currentlyRunningATask) { - // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a - // "too much recursion" error. - setTimeout(runIfPresent, 0, handle); - } else { - var task = tasksByHandle[handle]; - if (task) { - currentlyRunningATask = true; - try { - run(task); - } finally { - clearImmediate(handle); - currentlyRunningATask = false; - } - } - } - } - - function installNextTickImplementation() { - registerImmediate = function(handle) { - process.nextTick(function () { runIfPresent(handle); }); - }; - } - - function canUsePostMessage() { - // The test against `importScripts` prevents this implementation from being installed inside a web worker, - // where `global.postMessage` means something completely different and can't be used for this purpose. - if (global.postMessage && !global.importScripts) { - var postMessageIsAsynchronous = true; - var oldOnMessage = global.onmessage; - global.onmessage = function() { - postMessageIsAsynchronous = false; - }; - global.postMessage("", "*"); - global.onmessage = oldOnMessage; - return postMessageIsAsynchronous; - } - } - - function installPostMessageImplementation() { - // Installs an event handler on `global` for the `message` event: see - // * https://developer.mozilla.org/en/DOM/window.postMessage - // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages - - var messagePrefix = "setImmediate$" + Math.random() + "$"; - var onGlobalMessage = function(event) { - if (event.source === global && - typeof event.data === "string" && - event.data.indexOf(messagePrefix) === 0) { - runIfPresent(+event.data.slice(messagePrefix.length)); - } - }; - - if (global.addEventListener) { - global.addEventListener("message", onGlobalMessage, false); - } else { - global.attachEvent("onmessage", onGlobalMessage); - } - - registerImmediate = function(handle) { - global.postMessage(messagePrefix + handle, "*"); - }; - } - - function installMessageChannelImplementation() { - var channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - var handle = event.data; - runIfPresent(handle); - }; - - registerImmediate = function(handle) { - channel.port2.postMessage(handle); - }; - } - - function installReadyStateChangeImplementation() { - var html = doc.documentElement; - registerImmediate = function(handle) { - // Create a