From 8fd753e28d6b3d0919892391a97c238538a2e053 Mon Sep 17 00:00:00 2001 From: Anthony Perkins Date: Wed, 3 Feb 2021 12:43:53 +0000 Subject: [PATCH] Stop loading coc because node uses huge amounts of RAM --- coc-settings.json | 10 - pack/acp/opt/coc.nvim/.gitignore | 12 - pack/acp/opt/coc.nvim/LICENSE.md | 7 - pack/acp/opt/coc.nvim/Readme.md | 283 - pack/acp/opt/coc.nvim/autoload/coc.vim | 199 - pack/acp/opt/coc.nvim/autoload/coc/api.vim | 580 - pack/acp/opt/coc.nvim/autoload/coc/client.vim | 313 - pack/acp/opt/coc.nvim/autoload/coc/float.vim | 942 - pack/acp/opt/coc.nvim/autoload/coc/helper.vim | 56 - pack/acp/opt/coc.nvim/autoload/coc/list.vim | 292 - pack/acp/opt/coc.nvim/autoload/coc/rpc.vim | 127 - .../acp/opt/coc.nvim/autoload/coc/snippet.vim | 68 - pack/acp/opt/coc.nvim/autoload/coc/task.vim | 109 - .../opt/coc.nvim/autoload/coc/terminal.vim | 114 - pack/acp/opt/coc.nvim/autoload/coc/util.vim | 1117 - pack/acp/opt/coc.nvim/autoload/health/coc.vim | 97 - pack/acp/opt/coc.nvim/build/index.js | 91426 ---------------- pack/acp/opt/coc.nvim/data/schema.json | 1099 - pack/acp/opt/coc.nvim/doc/coc.cnx | 1769 - pack/acp/opt/coc.nvim/doc/coc.txt | 2999 - pack/acp/opt/coc.nvim/history.md | 1166 - pack/acp/opt/coc.nvim/package.json | 46 - pack/acp/opt/coc.nvim/plugin/coc.vim | 477 - pack/acp/opt/coc.nvim/terminateProcess.sh | 12 - vimrc | 20 - 25 files changed, 103340 deletions(-) delete mode 100644 coc-settings.json delete mode 100644 pack/acp/opt/coc.nvim/.gitignore delete mode 100644 pack/acp/opt/coc.nvim/LICENSE.md delete mode 100644 pack/acp/opt/coc.nvim/Readme.md delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/api.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/client.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/float.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/helper.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/list.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/rpc.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/snippet.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/task.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/terminal.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/coc/util.vim delete mode 100644 pack/acp/opt/coc.nvim/autoload/health/coc.vim delete mode 100644 pack/acp/opt/coc.nvim/build/index.js delete mode 100644 pack/acp/opt/coc.nvim/data/schema.json delete mode 100644 pack/acp/opt/coc.nvim/doc/coc.cnx delete mode 100644 pack/acp/opt/coc.nvim/doc/coc.txt delete mode 100644 pack/acp/opt/coc.nvim/history.md delete mode 100644 pack/acp/opt/coc.nvim/package.json delete mode 100644 pack/acp/opt/coc.nvim/plugin/coc.vim delete mode 100644 pack/acp/opt/coc.nvim/terminateProcess.sh diff --git a/coc-settings.json b/coc-settings.json deleted file mode 100644 index 7bba792..0000000 --- a/coc-settings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "languageserver": { - "go": { - "command": "gopls", - "rootPatterns": ["go.mod"], - "trace.server": "verbose", - "filetypes": ["go"] - } - } -} diff --git a/pack/acp/opt/coc.nvim/.gitignore b/pack/acp/opt/coc.nvim/.gitignore deleted file mode 100644 index a151978..0000000 --- a/pack/acp/opt/coc.nvim/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -lib -*.map -coverage -__pycache__ -.pyc -.log -src -publish.sh -doc/tags -doc/tags-cn -node_modules -src/__tests__/tags diff --git a/pack/acp/opt/coc.nvim/LICENSE.md b/pack/acp/opt/coc.nvim/LICENSE.md deleted file mode 100644 index bee2bf1..0000000 --- a/pack/acp/opt/coc.nvim/LICENSE.md +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2018-2018 by Qiming Zhao aaa - -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. diff --git a/pack/acp/opt/coc.nvim/Readme.md b/pack/acp/opt/coc.nvim/Readme.md deleted file mode 100644 index 3b53dd7..0000000 --- a/pack/acp/opt/coc.nvim/Readme.md +++ /dev/null @@ -1,283 +0,0 @@ -

- - Coc Logo - -

Make your Vim/Neovim as smart as VSCode.

-

- Software License - Actions - Doc - Gitter -

-

- ---- - -Gif - -_True snippet and additional text editing support_ - -## Why? - -- 🚀 **Fast**: [instant increment completion](https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources), increment buffer sync using buffer update events. -- 💎 **Reliable**: typed language, tested with CI. -- 🌟 **Featured**: [full LSP support](https://github.com/neoclide/coc.nvim/wiki/Language-servers#supported-features) -- ❤️ **Flexible**: [configured like VSCode](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file), [extensions work like in VSCode](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) - -## Quick Start - -Install [nodejs](https://nodejs.org/en/download/) >= 10.12: - -```sh -curl -sL install-node.now.sh/lts | bash -``` - -For [vim-plug](https://github.com/junegunn/vim-plug) users: - -```vim -" Use release branch (recommend) -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'} -``` - -in your `.vimrc` or `init.vim`, then restart Vim and run `:PlugInstall`. - -Checkout [Install -coc.nvim](https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim) for -more info. - -You **have to** install coc extension or configure language servers for -LSP support. - -Install extensions like: - - :CocInstall coc-json coc-tsserver - -Or configure language server in `coc-settings.json` opened by -`:CocConfig`, like: - -```json -{ - "languageserver": { - "go": { - "command": "gopls", - "rootPatterns": ["go.mod"], - "trace.server": "verbose", - "filetypes": ["go"] - } - } -} -``` - -Checkout wiki for more details: - -- [Completion with sources](https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources) -- [Using the configuration file](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file) -- [Using coc extensions](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) -- [Configure language servers](https://github.com/neoclide/coc.nvim/wiki/Language-servers) -- [F.A.Q](https://github.com/neoclide/coc.nvim/wiki/F.A.Q) - -Checkout `:h coc-nvim` for vim interface. - -## Example vim configuration - -Configuration is required to make coc.nvim easier to work with, since it -doesn't change your key-mappings or Vim options. This is done as much as -possible to avoid conflict with your other plugins. - -**❗️Important**: Some Vim plugins could change key mappings. Please use -`:verbose imap ` to make sure that your keymap has taken effect. - -```vim -" TextEdit might fail if hidden is not set. -set hidden - -" Some servers have issues with backup files, see #649. -set nobackup -set nowritebackup - -" Give more space for displaying messages. -set cmdheight=2 - -" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable -" delays and poor user experience. -set updatetime=300 - -" Don't pass messages to |ins-completion-menu|. -set shortmess+=c - -" Always show the signcolumn, otherwise it would shift the text each time -" diagnostics appear/become resolved. -if has("patch-8.1.1564") - " Recently vim can merge signcolumn and number column into one - set signcolumn=number -else - set signcolumn=yes -endif - -" Use tab for trigger completion with characters ahead and navigate. -" NOTE: Use command ':verbose imap ' to make sure tab is not mapped by -" other plugin before putting this into your config. -inoremap - \ pumvisible() ? "\" : - \ check_back_space() ? "\" : - \ coc#refresh() -inoremap pumvisible() ? "\" : "\" - -function! s:check_back_space() abort - let col = col('.') - 1 - return !col || getline('.')[col - 1] =~# '\s' -endfunction - -" Use to trigger completion. -if has('nvim') - inoremap coc#refresh() -else - inoremap coc#refresh() -endif - -" Make auto-select the first completion item and notify coc.nvim to -" format on enter, could be remapped by other vim plugin -inoremap pumvisible() ? coc#_select_confirm() - \: "\u\\=coc#on_enter()\" - -" Use `[g` and `]g` to navigate diagnostics -" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list. -nmap [g (coc-diagnostic-prev) -nmap ]g (coc-diagnostic-next) - -" GoTo code navigation. -nmap gd (coc-definition) -nmap gy (coc-type-definition) -nmap gi (coc-implementation) -nmap gr (coc-references) - -" Use K to show documentation in preview window. -nnoremap K :call show_documentation() - -function! s:show_documentation() - if (index(['vim','help'], &filetype) >= 0) - execute 'h '.expand('') - elseif (coc#rpc#ready()) - call CocActionAsync('doHover') - else - execute '!' . &keywordprg . " " . expand('') - endif -endfunction - -" Highlight the symbol and its references when holding the cursor. -autocmd CursorHold * silent call CocActionAsync('highlight') - -" Symbol renaming. -nmap rn (coc-rename) - -" Formatting selected code. -xmap f (coc-format-selected) -nmap f (coc-format-selected) - -augroup mygroup - autocmd! - " Setup formatexpr specified filetype(s). - autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected') - " Update signature help on jump placeholder. - autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp') -augroup end - -" Applying codeAction to the selected region. -" Example: `aap` for current paragraph -xmap a (coc-codeaction-selected) -nmap a (coc-codeaction-selected) - -" Remap keys for applying codeAction to the current buffer. -nmap ac (coc-codeaction) -" Apply AutoFix to problem on the current line. -nmap qf (coc-fix-current) - -" Map function and class text objects -" NOTE: Requires 'textDocument.documentSymbol' support from the language server. -xmap if (coc-funcobj-i) -omap if (coc-funcobj-i) -xmap af (coc-funcobj-a) -omap af (coc-funcobj-a) -xmap ic (coc-classobj-i) -omap ic (coc-classobj-i) -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)\" : "\" - -" Use CTRL-S for selections ranges. -" Requires 'textDocument/selectionRange' support of language server. -nmap (coc-range-select) -xmap (coc-range-select) - -" Add `:Format` command to format current buffer. -command! -nargs=0 Format :call CocAction('format') - -" Add `:Fold` command to fold current buffer. -command! -nargs=? Fold :call CocAction('fold', ) - -" Add `:OR` command for organize imports of the current buffer. -command! -nargs=0 OR :call CocAction('runCommand', 'editor.action.organizeImport') - -" Add (Neo)Vim's native statusline support. -" NOTE: Please see `:h coc-status` for integrations with external plugins that -" provide custom statusline: lightline.vim, vim-airline. -set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')} - -" Mappings for CoCList -" Show all diagnostics. -nnoremap a :CocList diagnostics -" Manage extensions. -nnoremap e :CocList extensions -" Show commands. -nnoremap c :CocList commands -" Find symbol of current document. -nnoremap o :CocList outline -" Search workspace symbols. -nnoremap s :CocList -I symbols -" Do default action for next item. -nnoremap j :CocNext -" Do default action for previous item. -nnoremap k :CocPrev -" Resume latest coc list. -nnoremap p :CocListResume -``` - -## Articles - -- [coc.nvim 插件体系介绍](https://zhuanlan.zhihu.com/p/65524706) -- [CocList 入坑指南](https://zhuanlan.zhihu.com/p/71846145) -- [Create coc.nvim extension to improve Vim experience](https://medium.com/@chemzqm/create-coc-nvim-extension-to-improve-vim-experience-4461df269173) -- [How to write a coc.nvim extension (and why)](https://samroeca.com/coc-plugin.html) - -## Trouble shooting - -Try these steps when you have problem with coc.nvim. - -- Make sure your Vim version >= 8.0 by command `:version`. -- If service failed to start, use command `:CocInfo` or `:checkhealth` on Neovim. -- Checkout the log of coc.nvim by command `:CocOpenLog`. -- When you have issues with the language server, it's recommended to [checkout - the output](https://github.com/neoclide/coc.nvim/wiki/Debug-language-server#using-output-channel). - -## Feedback - -- If you think Coc is useful, consider giving it a star. -- If you have a question, [ask on gitter](https://gitter.im/neoclide/coc.nvim) -- 中文用户请到 [中文 gitter](https://gitter.im/neoclide/coc-cn) 讨论 -- If something is not working, [create an - issue](https://github.com/neoclide/coc.nvim/issues/new). - - - -## License - -MIT diff --git a/pack/acp/opt/coc.nvim/autoload/coc.vim b/pack/acp/opt/coc.nvim/autoload/coc.vim deleted file mode 100644 index 2e2f45f..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc.vim +++ /dev/null @@ -1,199 +0,0 @@ -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 = [] -let s:is_vim = !has('nvim') -let s:error_sign = get(g:, 'coc_status_error_sign', has('mac') ? '❌ ' : 'E') -let s:warning_sign = get(g:, 'coc_status_warning_sign', has('mac') ? '⚠️ ' : 'W') -let s:select_api = exists('*nvim_select_popupmenu_item') -let s:callbacks = {} - -function! coc#expandable() abort - return coc#rpc#request('snippetCheck', [1, 0]) -endfunction - -function! coc#jumpable() abort - return coc#rpc#request('snippetCheck', [0, 1]) -endfunction - -function! coc#expandableOrJumpable() abort - return coc#rpc#request('snippetCheck', [1, 1]) -endfunction - -" add vim command to CocCommand list -function! coc#add_command(id, cmd, ...) - let config = {'id':a:id, 'cmd':a:cmd, 'title': get(a:,1,'')} - call add(g:coc_vim_commands, config) - if !coc#rpc#ready() | return | endif - call coc#rpc#notify('addCommand', [config]) -endfunction - -function! coc#refresh() abort - return "\=coc#start()\" -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 - return '' -endfunction - -function! coc#_insert_key(method, key, ...) abort - if get(a:, 1, 1) - call coc#_cancel() - endif - return "\=coc#rpc#".a:method."('doKeymap', ['".a:key."'])\" -endfunction - -function! coc#_complete() abort - let items = get(g:coc#_context, 'candidates', []) - let preselect = get(g:coc#_context, 'preselect', -1) - call complete( - \ g:coc#_context.start + 1, - \ items) - if s:select_api && len(items) && preselect != -1 - call nvim_select_popupmenu_item(preselect, v:false, v:false, {}) - endif - return '' -endfunction - -function! coc#_do_complete(start, items, preselect) - let g:coc#_context = { - \ 'start': a:start, - \ 'candidates': a:items, - \ 'preselect': a:preselect - \} - if mode() =~# 'i' && &paste != 1 - call feedkeys("\CocRefresh", 'i') - endif -endfunction - -function! coc#_select_confirm() abort - if !exists('*complete_info') - throw 'coc#_select_confirm requires complete_info function to work' - endif - let selected = complete_info()['selected'] - if selected != -1 - return "\" - elseif pumvisible() - return "\\" - endif - return '' -endfunction - -function! coc#_selected() - if !pumvisible() | return 0 | endif - return coc#rpc#request('hasSelected', []) -endfunction - -function! coc#_hide() abort - if !pumvisible() | return | endif - call feedkeys("\", 'in') -endfunction - -function! coc#_cancel() - " hack for close pum - if pumvisible() && &paste != 1 - let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []} - call feedkeys("\CocRefresh", 'i') - endif -endfunction - -function! coc#_select() abort - if !pumvisible() | return | endif - call feedkeys("\", 'in') -endfunction - -function! coc#start(...) - let opt = coc#util#get_complete_option() - call CocActionAsync('startCompletion', extend(opt, get(a:, 1, {}))) - return '' -endfunction - -" used for statusline -function! coc#status() - let info = get(b:, 'coc_diagnostic_info', {}) - let msgs = [] - if get(info, 'error', 0) - call add(msgs, s:error_sign . info['error']) - endif - if get(info, 'warning', 0) - call add(msgs, s:warning_sign . info['warning']) - endif - return s:trim(join(msgs, ' ') . ' ' . get(g:, 'coc_status', '')) -endfunction - -function! s:trim(str) - if exists('*trim') - return trim(a:str) - endif - return substitute(a:str, '\s\+$', '', '') -endfunction - -function! coc#config(section, value) - let g:coc_user_config[a:section] = a:value - call coc#rpc#notify('updateConfig', [a:section, a:value]) -endfunction - -function! coc#add_extension(...) - if a:0 == 0 | return | endif - call extend(g:coc_global_extensions, a:000) -endfunction - -function! coc#_watch(key) - if s:is_vim | return | endif - if index(s:watched_keys, a:key) == -1 - call add(s:watched_keys, a:key) - call dictwatcheradd(g:, a:key, function('s:GlobalChange')) - endif -endfunction - -function! coc#_unwatch(key) - if s:is_vim | return | endif - let idx = index(s:watched_keys, a:key) - if idx != -1 - call remove(s:watched_keys, idx) - call dictwatcherdel(g:, a:key, function('s:GlobalChange')) - endif -endfunction - -function! s:GlobalChange(dict, key, val) - call coc#rpc#notify('GlobalChange', [a:key, get(a:val, 'old', v:null), get(a:val, 'new', v:null)]) -endfunction - -function! coc#_map() - if !s:select_api | return | endif - for i in range(1, 9) - exe 'inoremap '.i.' call nvim_select_popupmenu_item('.(i - 1).', v:true, v:true, {})' - endfor -endfunction - -function! coc#_unmap() - if !s:select_api | return | endif - for i in range(1, 9) - exe 'silent! iunmap '.i - endfor -endfunction - -function! coc#on_notify(id, method, Cb) - let key = a:id. '-'.a:method - let s:callbacks[key] = a:Cb - call coc#rpc#notify('registNotification', [a:id, a:method]) -endfunction - -function! coc#do_notify(id, method, result) - let key = a:id. '-'.a:method - let Fn = s:callbacks[key] - if !empty(Fn) - call Fn(a:result) - endif -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/api.vim b/pack/acp/opt/coc.nvim/autoload/coc/api.vim deleted file mode 100644 index 47bf03d..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/api.vim +++ /dev/null @@ -1,580 +0,0 @@ -" ============================================================================ -" Description: Client api used by vim8 -" Author: Qiming Zhao -" Licence: MIT licence -" Last Modified: June 28, 2019 -" ============================================================================ -if has('nvim') | finish | endif -let s:funcs = {} -let s:prop_id = 1000 -let s:namespace_id = 1 -let s:namespace_cache = {} - -" helper {{ -function! s:buf_line_count(bufnr) abort - if bufnr('%') == a:bufnr - return line('$') - endif - if exists('*getbufline') - let lines = getbufline(a:bufnr, 1, '$') - return len(lines) - endif - let curr = bufnr('%') - execute 'buffer '.a:bufnr - let n = line('$') - execute 'buffer '.curr - return n -endfunction - -function! s:execute(cmd) - if a:cmd =~# '^echo' - execute a:cmd - else - silent! execute a:cmd - endif -endfunction -" }}" - -" nvim client methods {{ -function! s:funcs.set_current_dir(dir) abort - execute 'cd '.a:dir -endfunction - -function! s:funcs.set_var(name, value) abort - execute 'let g:'.a:name.'= a:value' -endfunction - -function! s:funcs.del_var(name) abort - execute 'unlet g:'.a:name -endfunction - -function! s:funcs.set_option(name, value) abort - execute 'let &'.a:name.' = a:value' -endfunction - -function! s:funcs.set_current_buf(bufnr) abort - if !bufexists(a:bufnr) | return | endif - execute 'buffer '.a:bufnr -endfunction - -function! s:funcs.set_current_win(win_id) abort - let [tabnr, winnr] = win_id2tabwin(a:win_id) - if tabnr == 0 | return | endif - execute 'normal! '.tabnr.'gt' - execute winnr.' wincmd w' -endfunction - -function! s:funcs.set_current_tabpage(tabnr) abort - execute 'normal! '.a:tabnr.'gt' -endfunction - -function! s:funcs.list_wins() abort - return map(getwininfo(), 'v:val["winid"]') -endfunction - -function! s:funcs.call_atomic(calls) - let res = [] - for [key, arglist] in a:calls - let name = key[5:] - try - call add(res, call(s:funcs[name], arglist)) - catch /.*/ - return [res, v:exception] - endtry - endfor - return [res, v:null] -endfunction - -function! s:funcs.set_client_info(...) abort -endfunction - -function! s:funcs.subscribe(...) abort -endfunction - -function! s:funcs.unsubscribe(...) abort -endfunction - -function! s:funcs.call_function(method, args) abort - return call(a:method, a:args) -endfunction - -function! s:funcs.call_dict_function(dict, method, args) abort - return call(a:method, a:args, a:dict) -endfunction - -function! s:funcs.command(command) abort - " command that could cause cursor vanish - if a:command =~# '^echo' || a:command =~# '^redraw' || a:command =~# '^sign place' - call timer_start(0, {-> s:execute(a:command)}) - else - execute a:command - endif -endfunction - -function! s:funcs.eval(expr) abort - return eval(a:expr) -endfunction - -function! s:funcs.get_api_info() - let names = coc#api#func_names() - return [1, {'functions': map(names, '{"name": "nvim_".v:val}')}] -endfunction - -function! s:funcs.list_bufs() - return map(getbufinfo({'buflisted': 1}), 'v:val["bufnr"]') -endfunction - -function! s:funcs.feedkeys(keys, mode, escape_csi) - call feedkeys(a:keys, a:mode) -endfunction - -function! s:funcs.list_runtime_paths() - return split(&runtimepath, ',') -endfunction - -function! s:funcs.command_output(cmd) - return execute(a:cmd) -endfunction - -function! s:funcs.get_current_line() - return getline('.') -endfunction - -function! s:funcs.set_current_line(line) - call setline('.', a:line) -endfunction - -function! s:funcs.del_current_line(line) - execute 'normal! dd' -endfunction - -function! s:funcs.get_var(var) - return get(g:, a:var, v:null) -endfunction - -function! s:funcs.get_vvar(var) - return get(v:, a:var, v:null) -endfunction - -function! s:funcs.get_option(name) - return eval('&'.a:name) -endfunction - -function! s:funcs.get_current_buf() - return bufnr('%') -endfunction - -function! s:funcs.get_current_win() - return win_getid() -endfunction - -function! s:funcs.get_current_tabpage() - return tabpagenr() -endfunction - -function! s:funcs.list_tabpages() - return range(1, tabpagenr('$')) -endfunction - -function! s:funcs.get_mode() - return {'blocking': v:false, 'mode': mode()} -endfunction - -function! s:funcs.strwidth(str) - return strwidth(a:str) -endfunction - -function! s:funcs.out_write(str) - echon a:str -endfunction - -function! s:funcs.err_write(str) - echoerr a:str -endfunction - -function! s:funcs.err_writeln(str) - echoerr a:str -endfunction - -function! s:funcs.create_namespace(name) abort - if empty(a:name) - let id = s:namespace_id - let s:namespace_id = s:namespace_id + 1 - return id - endif - let id = get(s:namespace_cache, a:name, 0) - if !id - let id = s:namespace_id - let s:namespace_id = s:namespace_id + 1 - let s:namespace_cache[a:name] = id - endif - return id -endfunction -" }} - -" buffer methods {{ -function! s:funcs.buf_set_option(bufnr, name, val) - let val = a:val - if val is v:true - let val = 1 - elseif val is v:false - let val = 0 - endif - return setbufvar(a:bufnr, '&'.a:name, val) -endfunction - -function! s:funcs.buf_get_changedtick(bufnr) - return getbufvar(a:bufnr, 'changedtick') -endfunction - -function! s:funcs.buf_is_valid(bufnr) - return bufloaded(a:bufnr) ? v:true : v:false -endfunction - -function! s:funcs.buf_get_mark(bufnr, name) - let nr = bufnr('%') - if a:bufnr != 0 || a:bufnr != nr - throw 'buf_get_mark support current buffer only' - endif - return [line("'" . a:name), col("'" . a:name)] -endfunction - -function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEnd) abort - if !has('textprop') - 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 - endif - let total = strlen(getbufline(bufnr, a:line + 1)[0]) - let end = a:colEnd - if end == -1 - let end = total - else - let end = min([end, total]) - endif - if end <= a:colStart - return - endif - let id = s:prop_id - let s:prop_id = id + 1 - try - call prop_add(a:line + 1, a:colStart + 1, {'length': end - a:colStart, 'bufnr': bufnr, 'type': key, 'id': id}) - catch /^Vim\%((\a\+)\)\=:E967/ - " ignore 967 - endtry -endfunction - -function! s:funcs.buf_clear_namespace(bufnr, srcId, startLine, endLine) abort - if !has('textprop') - return - endif - 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 - 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 - endif -endfunction - -function! s:funcs.buf_line_count(bufnr) abort - return s:buf_line_count(a:bufnr) -endfunction - -function! s:funcs.buf_attach(...) - " not supported - return 1 -endfunction - -function! s:funcs.buf_detach() - " not supported - return 1 -endfunction - -function! s:funcs.buf_get_lines(bufnr, start, end, strict) abort - let lines = getbufline(a:bufnr, 1, '$') - let start = a:start < 0 ? a:start + 1 : a:start - let end = a:end < 0 ? a:end + 1 : a:end - if a:strict && end > len(lines) - throw 'line number out of range: '. end - endif - return lines[start : end - 1] -endfunction - -function! s:funcs.buf_set_lines(bufnr, start, end, strict, ...) abort - if !bufloaded(a:bufnr) - return - endif - let replacement = get(a:, 1, []) - let lineCount = s:buf_line_count(a:bufnr) - let startLnum = a:start >= 0 ? a:start + 1 : lineCount + a:start + 1 - let end = a:end >= 0 ? a:end : lineCount + a:end + 1 - if end == lineCount + 1 - let end = lineCount - endif - let delCount = end - (startLnum - 1) - let changeBuffer = 0 - let curr = bufnr('%') - if a:bufnr != curr && !exists('*setbufline') - let changeBuffer = 1 - exe 'buffer '.a:bufnr - endif - if a:bufnr == curr || changeBuffer - " replace - let storeView = winsaveview() - if delCount == len(replacement) - call setline(startLnum, replacement) - else - if len(replacement) - call append(startLnum - 1, replacement) - endif - if delCount - let start = startLnum + len(replacement) - let saved_reg = @" - silent execute start . ','.(start + delCount - 1).'d' - let @" = saved_reg - endif - endif - call winrestview(storeView) - if changeBuffer - exe 'buffer '.curr - endif - elseif exists('*setbufline') - " replace - if delCount == len(replacement) - " 8.0.1039 - call setbufline(a:bufnr, startLnum, replacement) - else - if len(replacement) - " 8.10037 - call appendbufline(a:bufnr, startLnum - 1, replacement) - endif - if delCount - let start = startLnum + len(replacement) - "8.1.0039 - call deletebufline(a:bufnr, start, start + delCount - 1) - endif - endif - endif -endfunction - -function! s:funcs.buf_set_name(bufnr, name) abort - let nr = bufnr('%') - if a:bufnr != nr - throw 'buf_set_name support current buffer only' - else - execute '0f' - execute 'file '.fnameescape(a:name) - endif -endfunction - -function! s:funcs.buf_get_var(bufnr, name) - return getbufvar(a:bufnr, a:name) -endfunction - -function! s:funcs.buf_set_var(bufnr, name, val) - if !bufloaded(a:bufnr) | return | endif - call setbufvar(a:bufnr, a:name, a:val) -endfunction - -function! s:funcs.buf_del_var(bufnr, name) - call setbufvar(a:bufnr, a:name, v:null) -endfunction - -function! s:funcs.buf_get_option(bufnr, name) - return getbufvar(a:bufnr, '&'.a:name) -endfunction - -function! s:funcs.buf_get_name(bufnr) - return bufname(a:bufnr) -endfunction -" }} - -" window methods {{ -function! s:funcs.win_get_buf(winid) - return winbufnr(a:winid) -endfunction - -function! s:funcs.win_get_position(win_id) abort - let [row, col] = win_screenpos(a:win_id) - if row == 0 && col == 0 - throw 'Invalid window '.a:win_id - endif - return [row - 1, col - 1] -endfunction - -function! s:funcs.win_get_height(win_id) abort - return winheight(a:win_id) -endfunction - -function! s:funcs.win_get_width(win_id) abort - return winwidth(a:win_id) -endfunction - -if exists('*win_execute') - function! s:win_execute(win_id, cmd, ...) abort - let ref = get(a:000, 0, v:null) - let cmd = ref is v:null ? a:cmd : 'let ref["out"] = ' . a:cmd - call win_execute(a:win_id, cmd) - endfunction -else - function! s:win_execute(win_id, cmd, ...) abort - let ref = get(a:000, 0, v:null) - let cmd = ref is v:null ? a:cmd : 'let ref["out"] = ' . a:cmd - let winid = win_getid() - if winid == a:win_id - execute cmd - else - let goto_status = win_gotoid(a:win_id) - if !goto_status - return - endif - execute cmd - call win_gotoid(winid) - endif - endfunction -endif - -function! s:funcs.win_get_cursor(win_id) abort - let ref = {} - call s:win_execute(a:win_id, "[line('.'), col('.')-1]", ref) - return ref['out'] -endfunction - -function! s:funcs.win_get_var(win_id, name) abort - return gettabwinvar(0, a:win_id, a:name) -endfunction - -function! s:funcs.win_set_width(win_id, width) abort - return s:win_execute(a:win_id, 'vertical resize '.a:width) -endfunction - -function! s:funcs.win_set_buf(win_id, buf_id) abort - return s:win_execute(a:win_id, 'buffer '.a:buf_id) -endfunction - -function! s:funcs.win_get_option(win_id, name) abort - return gettabwinvar(0, a:win_id, '&'.a:name) -endfunction - -function! s:funcs.win_set_height(win_id, height) abort - return s:win_execute(a:win_id, 'resize '.a:height) -endfunction - -function! s:funcs.win_set_option(win_id, name, value) abort - let val = a:value - if val is v:true - let val = 1 - elseif val is v:false - let val = 0 - endif - call setwinvar(a:win_id, '&'.a:name, val) -endfunction - -function! s:funcs.win_set_var(win_id, name, value) abort - call setwinvar(a:win_id, a:name, a:value) -endfunction - -function! s:funcs.win_del_var(win_id, name) abort - call settabwinvar(0, a:win_id, a:name, v:null) -endfunction - -function! s:funcs.win_is_valid(win_id) abort - let info = getwininfo(a:win_id) - return !empty(info) -endfunction - -function! s:funcs.win_get_number(win_id) abort - let info = getwininfo(a:win_id) - if empty(info) - throw 'Invalid window id '.a:win_id - endif - return info[0]['winnr'] -endfunction - -function! s:funcs.win_set_cursor(win_id, pos) abort - let [line, col] = a:pos - call s:win_execute(a:win_id, 'call cursor('.line.','.(col + 1).')') -endfunction - -function! s:funcs.win_close(win_id, ...) abort - call s:win_execute(a:win_id, 'close!') -endfunction - -function! s:funcs.win_get_tabpage(win_id) abort - let info = getwininfo(a:win_id) - if !info - throw 'Invalid window id '.a:win_id - endif - return info[0]['tabnr'] -endfunction -" }} - -" tabpage methods {{ -function! s:funcs.tabpage_get_number(id) - return a:id -endfunction - -function! s:funcs.tabpage_list_wins(tabnr) - let info = getwininfo() - return map(filter(info, 'v:val["tabnr"] == a:tabnr'), 'v:val["winid"]') -endfunction - -function! s:funcs.tabpage_get_var(tabnr, name) - return gettabvar(a:tabnr, a:name, v:null) -endfunction - -function! s:funcs.tabpage_set_var(tabnr, name, value) - call settabvar(a:tabnr, a:name, a:value) -endfunction - -function! s:funcs.tabpage_del_var(tabnr, name) - call settabvar(a:tabnr, a:name, v:null) -endfunction - -function! s:funcs.tabpage_is_valid(tabnr) - let max = tabpagenr('$') - return a:tabnr <= max -endfunction - -function! s:funcs.tabpage_get_win(tabnr) - let wnr = tabpagewinnr(a:tabnr) - return win_getid(wnr, a:tabnr) -endfunction -" }} - -function! coc#api#func_names() abort - return keys(s:funcs) -endfunction - -function! coc#api#call(method, args) abort - let err = v:null - let res = v:null - try - let res = call(s:funcs[a:method], a:args) - catch /.*/ - let err = v:exception - endtry - return [err, res] -endfunction - -function! coc#api#notify(method, args) abort - call call(s:funcs[a:method], a:args) -endfunction -" vim: set sw=2 ts=2 sts=2 et tw=78 foldmarker={{,}} foldmethod=marker foldlevel=0: diff --git a/pack/acp/opt/coc.nvim/autoload/coc/client.vim b/pack/acp/opt/coc.nvim/autoload/coc/client.vim deleted file mode 100644 index 3b945aa..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/client.vim +++ /dev/null @@ -1,313 +0,0 @@ -let s:root = expand(':h:h:h') -let s:is_vim = !has('nvim') -let s:is_win = has("win32") || has("win64") -let s:clients = {} - -if get(g:, 'node_client_debug', 0) - let $NODE_CLIENT_LOG_LEVEL = 'debug' - if exists('$NODE_CLIENT_LOG_FILE') - let s:logfile = resolve($NODE_CLIENT_LOG_FILE) - else - let s:logfile = tempname() - let $NODE_CLIENT_LOG_FILE = s:logfile - endif -endif - -" create a client -function! coc#client#create(name, command) - let client = {} - let client['command'] = a:command - let client['name'] = a:name - let client['running'] = 0 - let client['async_req_id'] = 1 - let client['async_callbacks'] = {} - " vim only - let client['channel'] = v:null - " neovim only - let client['chan_id'] = 0 - let client['start'] = function('s:start', [], client) - let client['request'] = function('s:request', [], client) - let client['notify'] = function('s:notify', [], client) - let client['request_async'] = function('s:request_async', [], client) - let client['on_async_response'] = function('s:on_async_response', [], client) - let s:clients[a:name] = client - return client -endfunction - -function! s:start() dict - if self.running | return | endif - if !isdirectory(getcwd()) - echohl Error | echon '[coc.nvim] Current cwd is not a valid directory.' | echohl None - return - endif - let timeout = string(get(g:, 'coc_channel_timeout', 30)) - let disable_warning = string(get(g:, 'coc_disable_startup_warning', 0)) - let tmpdir = fnamemodify(tempname(), ':p:h') - if s:is_vim - let options = { - \ 'in_mode': 'json', - \ 'out_mode': 'json', - \ 'err_mode': 'nl', - \ 'err_cb': {channel, message -> s:on_stderr(self.name, split(message, "\n"))}, - \ 'exit_cb': {channel, code -> s:on_exit(self.name, code)}, - \ 'env': { - \ 'NODE_NO_WARNINGS': '1', - \ 'VIM_NODE_RPC': '1', - \ 'COC_NVIM': '1', - \ 'COC_CHANNEL_TIMEOUT': timeout, - \ 'COC_NO_WARNINGS': disable_warning, - \ 'TMPDIR': tmpdir, - \ } - \} - if has("patch-8.1.350") - let options['noblock'] = 1 - endif - let job = job_start(self.command, options) - let status = job_status(job) - if status !=# 'run' - let self.running = 0 - echohl Error | echom 'Failed to start '.self.name.' service' | echohl None - return - endif - 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'), - \ } - " 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) - 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 chan_id <= 0 - echohl Error | echom 'Failed to start '.self.name.' service' | echohl None - return - endif - let self['chan_id'] = chan_id - let self['running'] = 1 - endif -endfunction - -function! s:on_stderr(name, msgs) - if get(g:, 'coc_vim_leaving', 0) | return | endif - if get(g:, 'coc_disable_uncaught_error', 0) | return | endif - let data = filter(copy(a:msgs), '!empty(v:val)') - if empty(data) | return | endif - let client = a:name ==# 'coc' ? '[coc.nvim]' : '['.a:name.']' - let data[0] = client.': '.data[0] - call coc#util#echo_messages('Error', data) -endfunction - -function! s:on_exit(name, code) abort - if get(g:, 'coc_vim_leaving', 0) | return | endif - let client = get(s:clients, a:name, v:null) - if empty(client) | return | endif - if client['running'] != 1 | return | endif - let client['running'] = 0 - let client['chan_id'] = 0 - let client['channel'] = v:null - let client['async_req_id'] = 1 - if a:code != 0 && a:code != 143 - echohl Error | echom 'client '.a:name. ' abnormal exit with: '.a:code | echohl None - endif -endfunction - -function! coc#client#get_client(name) abort - return get(s:clients, a:name, v:null) -endfunction - -function! coc#client#get_channel(client) - if s:is_vim - return a:client['channel'] - endif - return a:client['chan_id'] -endfunction - -function! s:request(method, args) dict - let channel = coc#client#get_channel(self) - if empty(channel) | return '' | endif - try - if s:is_vim - let res = ch_evalexpr(channel, [a:method, a:args], {'timeout': 60 * 1000}) - if type(res) == 1 && res ==# '' - throw 'request '.a:method. ' '.string(a:args).' timeout after 60s' - endif - let [l:errmsg, res] = res - if !empty(l:errmsg) - throw l:errmsg - else - return res - endif - else - return call('rpcrequest', [channel, a:method] + a:args) - endif - catch /.*/ - if v:exception =~# 'E475' - if get(g:, 'coc_vim_leaving', 0) | return | endif - echohl Error | echom '['.self.name.'] server connection lost' | echohl None - let name = self.name - call s:on_exit(name, 0) - execute 'silent do User ConnectionLost'.toupper(name[0]).name[1:] - elseif v:exception =~# 'E12' - " neovim's bug, ignore it - else - echohl Error | echo 'Error on request ('.a:method.'): '.v:exception | echohl None - endif - endtry -endfunction - -function! s:notify(method, args) dict - let channel = coc#client#get_channel(self) - if empty(channel) - return '' - endif - try - if s:is_vim - call ch_sendraw(channel, json_encode([0, [a:method, a:args]])."\n") - else - call call('rpcnotify', [channel, a:method] + a:args) - endif - catch /.*/ - if v:exception =~# 'E475' - if get(g:, 'coc_vim_leaving', 0) - return - endif - echohl Error | echom '['.self.name.'] server connection lost' | echohl None - let name = self.name - call s:on_exit(name, 0) - execute 'silent do User ConnectionLost'.toupper(name[0]).name[1:] - elseif v:exception =~# 'E12' - " neovim's bug, ignore it - else - echohl Error | echo 'Error on notify ('.a:method.'): '.v:exception | echohl None - endif - endtry -endfunction - -function! s:request_async(method, args, cb) dict - let channel = coc#client#get_channel(self) - if empty(channel) | return '' | endif - if type(a:cb) != 2 - echohl Error | echom '['.self['name'].'] Callback should be function' | echohl None - return - endif - let id = self.async_req_id - let self.async_req_id = id + 1 - let self.async_callbacks[id] = a:cb - call self['notify']('nvim_async_request_event', [id, a:method, a:args]) -endfunction - -function! s:on_async_response(id, resp, isErr) dict - let Callback = get(self.async_callbacks, a:id, v:null) - if empty(Callback) - " should not happen - echohl Error | echom 'callback not found' | echohl None - return - endif - call remove(self.async_callbacks, a:id) - if a:isErr - call call(Callback, [a:resp, v:null]) - else - call call(Callback, [v:null, a:resp]) - endif -endfunction - -function! coc#client#is_running(name) abort - let client = get(s:clients, a:name, v:null) - if empty(client) | return 0 | endif - if !client['running'] | return 0 | endif - if s:is_vim - let status = job_status(ch_getjob(client['channel'])) - return status ==# 'run' - else - let chan_id = client['chan_id'] - let [code] = jobwait([chan_id], 10) - return code == -1 - endif -endfunction - -function! coc#client#stop(name) abort - let client = get(s:clients, a:name, v:null) - if empty(client) | return 1 | endif - let running = coc#client#is_running(a:name) - if !running - echohl WarningMsg | echom 'client '.a:name. ' not running.' | echohl None - return 1 - endif - if s:is_vim - call job_stop(ch_getjob(client['channel']), 'term') - else - call jobstop(client['chan_id']) - endif - sleep 200m - if coc#client#is_running(a:name) - echohl Error | echom 'client '.a:name. ' stop failed.' | echohl None - return 0 - endif - call s:on_exit(a:name, 0) - echohl MoreMsg | echom 'client '.a:name.' stopped!' | echohl None - return 1 -endfunction - -function! coc#client#request(name, method, args) - let client = get(s:clients, a:name, v:null) - if !empty(client) - return client['request'](a:method, a:args) - endif -endfunction - -function! coc#client#notify(name, method, args) - let client = get(s:clients, a:name, v:null) - if !empty(client) - call client['notify'](a:method, a:args) - endif -endfunction - -function! coc#client#request_async(name, method, args, cb) - let client = get(s:clients, a:name, v:null) - if !empty(client) - call client['request_async'](a:method, a:args, a:cb) - endif -endfunction - -function! coc#client#on_response(name, id, resp, isErr) - let client = get(s:clients, a:name, v:null) - if !empty(client) - call client['on_async_response'](a:id, a:resp, a:isErr) - endif -endfunction - -function! coc#client#restart(name) abort - let stopped = coc#client#stop(a:name) - if !stopped | return | endif - let client = get(s:clients, a:name, v:null) - if !empty(client) - call client['start']() - endif -endfunction - -function! coc#client#restart_all() - for key in keys(s:clients) - call coc#client#restart(key) - endfor -endfunction - -function! coc#client#open_log() - if !get(g:, 'node_client_debug', 0) - echohl Error | echon '[coc.nvim] use let g:node_client_debug = 1 in your vimrc to enabled debug mode.' | echohl None - return - endif - execute 'vs '.s:logfile -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/float.vim b/pack/acp/opt/coc.nvim/autoload/coc/float.vim deleted file mode 100644 index bb66324..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/float.vim +++ /dev/null @@ -1,942 +0,0 @@ -" Related to float window create -let s:is_vim = !has('nvim') -let s:borderchars = get(g:, 'coc_borderchars', - \ ['─', '│', '─', '│', '┌', '┐', '┘', '└']) -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 -" winvar: border array of numbers, button boolean - -" detect if there's float window/popup created by coc.nvim -function! coc#float#has_float() abort - if s:is_vim - if !exists('*popup_list') - return 0 - endif - let arr = filter(popup_list(), 'getwinvar(v:val,"float",0)&&popup_getpos(v:val)["visible"]') - return !empty(arr) - endif - for i in range(1, winnr('$')) - if getwinvar(i, 'float') - return 1 - endif - endfor - return 0 -endfunction - -function! coc#float#close_all() abort - if !has('nvim') && exists('*popup_clear') - call popup_clear() - return - endif - let winids = coc#float#get_float_win_list() - for id in winids - call coc#float#close(id) - endfor -endfunction - -function! coc#float#jump() abort - if s:is_vim - return - endif - let winids = coc#float#get_float_win_list() - if !empty(winids) - call win_gotoid(winids[0]) - 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. -" - width: content width without border and title. -" - height: content height without border and title. -" - 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. -function! coc#float#create_float_win(winid, bufnr, config) abort - call coc#float#close_auto_hide_wins(a:winid) - " 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, { - \ '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', ''), - \ } - if !s:empty_border(get(a:config, 'border', [])) - let opts['border'] = a:config['border'] - endif - call popup_setoptions(a:winid, opts) - 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_config(a:winid, config) - call coc#float#nvim_create_related(a:winid, config, a:config) - return [a:winid, winbufnr(a:winid)] - 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 opts = { - \ 'title': title, - \ 'line': line, - \ 'col': col, - \ 'padding': empty(title) ? [0, 1, 0, 1] : [0, 0, 0, 0], - \ 'borderchars': s:borderchars, - \ 'highlight': 'CocFloating', - \ 'fixed': 1, - \ 'cursorline': get(a:config, 'cursorline', 0), - \ 'minwidth': a:config['width'], - \ 'minheight': a:config['height'], - \ 'maxwidth': a:config['width'], - \ 'maxheight': a:config['height'] - \ } - if get(a:config, 'close', 0) - let opts['close'] = 'button' - endif - if !s:empty_border(get(a:config, 'border', [])) - let opts['border'] = a:config['border'] - endif - let winid = popup_create(bufnr, opts) - if winid == 0 - return [] - endif - 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') - call setwinvar(winid, '&signcolumn', 'no') - " no left border - if s:empty_border(get(a:config, 'border', [])) || a:config['border'][3] == 0 - call setwinvar(winid, '&foldcolumn', 1) - endif - 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, '&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)] -endfunction - -function! coc#float#valid(winid) abort - if a:winid == 0 || type(a:winid) != 0 - return 0 - endif - if s:is_vim - return s:popup_visible(a:winid) - 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 -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 - endif - if s:is_vim - noa let bufnr = bufadd('') - noa call bufload(bufnr) - else - noa let bufnr = nvim_create_buf(v:false, v:true) - 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 -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') - 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 opt = { - \ 'relative': a:config['relative'], - \ 'width': width, - \ 'height': height, - \ 'row': row, - \ 'col': col, - \ 'focusable': v:false, - \ 'style': 'minimal', - \ } - let winid = nvim_open_win(bufnr, 0, opt) - if !winid - return - 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 - let list = [] - if a:border[0] - let top = (a:border[3] ? s:borderchars[4]: '') - \.repeat(s:borderchars[0], a:width) - \.(a:border[1] ? s:borderchars[5] : '') - if !empty(a:title) - let top = coc#helper#str_compose(top, 1, a:title.' ') - endif - call add(list, top) - endif - let mid = (a:border[3] ? s:borderchars[3]: '') - \.repeat(' ', a:width) - \.(a:border[1] ? s:borderchars[1] : '') - call extend(list, repeat([mid], a:height)) - if a:border[2] - let bot = (a:border[3] ? s:borderchars[7]: '') - \.repeat(s:borderchars[2], a:width) - \.(a:border[1] ? s:borderchars[6] : '') - call add(list, bot) - endif - return list -endfunction - -" Create float window for input -function! coc#float#create_prompt_win(title, default) 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]) - if width == &columns - 2 - let col = 0 - curr - else - let col = curr + width <= &columns - 2 ? 0 : &columns - s:prompt_win_width - endif - let config = { - \ 'relative': 'cursor', - \ 'width': width, - \ 'height': 1, - \ 'row': 0, - \ 'col': col, - \ 'style': 'minimal', - \ } - let winid = nvim_open_win(bufnr, 0, config) - if winid == 0 - return [] - 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 - -function! coc#float#close_i(winid) abort - call coc#float#close(a:winid) - 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)}) - 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 -endfunction - -" Float window id on current tab. -" return 0 if not found -function! coc#float#get_float_win() abort - if has('nvim') - for i in range(1, winnr('$')) - let id = win_getid(i) - let config = nvim_win_get_config(id) - if (!empty(config) && config['focusable'] == v:true && !empty(config['relative'])) - if !getwinvar(id, 'button', 0) - return id - endif - endif - endfor - elseif exists('*popup_list') - let arr = filter(popup_list(), 'popup_getpos(v:val)["visible"]') - if !empty(arr) - return arr[0] - endif - endif - return 0 -endfunction - -function! coc#float#get_float_win_list() abort - if s:is_vim && exists('*popup_list') - return filter(popup_list(), 'popup_getpos(v:val)["visible"]') - elseif has('nvim') && exists('*nvim_win_get_config') - let res = [] - for i in range(1, winnr('$')) - 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 - endif - endfor - return res - endif - return [] -endfunction - -" Check if a float window is scrollable -function! coc#float#scrollable(winid) abort - let bufnr = winbufnr(a:winid) - if bufnr == -1 - return 0 - 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 - let ch = coc#float#content_height(bufnr, pos['core_width'], getwinvar(a:winid, '&wrap')) - return ch > pos['core_height'] - else - let height = nvim_win_get_height(a:winid) - let width = nvim_win_get_width(a:winid) - if width > 1 && getwinvar(a:winid, '&foldcolumn', 0) - " since we use foldcolumn for left pading - let width = width - 1 - endif - let ch = coc#float#content_height(bufnr, width, getwinvar(a:winid, '&wrap')) - return ch > height - endif -endfunction - -function! coc#float#has_scroll() abort - let win_ids = filter(coc#float#get_float_win_list(), 'coc#float#scrollable(v:val)') - return !empty(win_ids) -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' - 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) - 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)}) - 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) - 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 -endfunction - -function! s:popup_visible(id) abort - let pos = popup_getpos(a:id) - if !empty(pos) && get(pos, 'visible', 0) - return 1 - endif - return 0 -endfunction - -function! s:convert_config_nvim(config) abort - let result = coc#helper#dict_omit(a:config, ['title', 'border', 'cursorline', 'autohide', 'close']) - let border = get(a:config, 'border', []) - if !s:empty_border(border) - if result['relative'] ==# 'cursor' && result['row'] < 0 - " move top when has bottom border - if get(border, 2, 0) - let result['row'] = result['row'] - 1 - endif - else - " move down when has top border - if get(border, 0, 0) - let result['row'] = result['row'] + 1 - endif - endif - " move right when has left border - if get(border, 3, 0) - let result['col'] = result['col'] + 1 - endif - let result['width'] = result['width'] + 1 - get(border,3, 0) - else - let result['width'] = result['width'] + 1 - endif - return result -endfunction - -" Close windows that could auto hide -function! coc#float#close_auto_hide_wins(...) abort - let winids = coc#float#get_float_win_list() - let except = get(a:, 1, 0) - for id in winids - if except && id == except - continue - endif - if getwinvar(id, 'autohide', 0) - call coc#float#close(id) - endif - 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 - endif - if !a:wrap - return has('nvim') ? nvim_buf_line_count(a:bufnr) : len(getbufline(a:bufnr, 1, '$')) - endif - let lines = has('nvim') ? nvim_buf_get_lines(a:bufnr, 0, -1, 0) : getbufline(a:bufnr, 1, '$') - let total = 0 - for line in lines - let dw = max([1, strdisplaywidth(line)]) - let total += float2nr(ceil(str2float(string(dw))/a:width)) - endfor - 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()) - endif -endfunction - -" Close related windows for neovim. -function! coc#float#nvim_close_related(winid) abort - if !has('nvim') || !a:winid - return - endif - 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) - 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 - 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) - else - noa let sbuf = nvim_create_buf(v:false, v:true) - call setbufvar(sbuf, '&bufhidden', 'wipe') - 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 - 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 -endfunction - -" Dimension of window with lines relative to cursor -" Width & height excludes border & padding -function! coc#float#get_config_cursor(lines, config) abort - let preferTop = get(a:config, 'preferTop', 0) - let title = get(a:config, 'title', '') - let border = get(a:config, 'border', [0, 0, 0, 0]) - if s:empty_border(border) && len(title) - let border = [1, 1, 1, 1] - endif - let bh = get(border, 0, 0) + get(border, 2, 0) - let vh = &lines - &cmdheight - 1 - if vh <= 0 - return v:null - endif - let maxWidth = min([get(a:config, 'maxWidth', 80), &columns - 1]) - if maxWidth < 3 - return v:null - endif - let maxHeight = min([get(a:config, 'maxHeight', 80), vh]) - let ch = 0 - let width = 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() - " How much we should move left - let offsetX = 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]) - if height <= bh - return v:null - endif - let col = - max([offsetX, colIdx - (&columns - 1 - width)]) - let row = showTop ? - height : 1 - return { - \ 'row': row, - \ 'col': col, - \ 'width': width - 2, - \ 'height': height - bh - \ } -endfunction - -function! coc#float#get_config_pum(lines, pumconfig, maxwidth) abort - if !pumvisible() - 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 - if maxWidth <= 2 || maxHeight < 1 - return v:null - endif - let ch = 0 - let width = 0 - 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 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' - \ } -endfunction - -function! s:empty_border(border) abort - if empty(a:border) - return 1 - endif - if a:border[0] == 0 && a:border[1] == 0 && a:border[2] == 0 && a:border[3] == 0 - return 1 - endif - return 0 -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/helper.vim b/pack/acp/opt/coc.nvim/autoload/coc/helper.vim deleted file mode 100644 index ae7eab2..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/helper.vim +++ /dev/null @@ -1,56 +0,0 @@ -" Helper methods for viml - -" insert inserted to line at position, use ... when result is too long -" line should only contains character has strwidth equals 1 -function! coc#helper#str_compose(line, position, inserted) abort - let width = strwidth(a:line) - let text = a:inserted - let res = a:line - let need_truncate = a:position + strwidth(text) + 1 > width - if need_truncate - let remain = width - a:position - 3 - if remain < 2 - " use text for full line, use first & end of a:line, ignore position - let res = strcharpart(a:line, 0, 1) - let w = strwidth(res) - for i in range(strchars(text)) - let c = strcharpart(text, i, 1) - let a = strwidth(c) - if w + a <= width - 1 - let w = w + a - let res = res.c - endif - endfor - let res = res.strcharpart(a:line, w) - else - let res = strcharpart(a:line, 0, a:position) - let w = strwidth(res) - for i in range(strchars(text)) - let c = strcharpart(text, i, 1) - let a = strwidth(c) - if w + a <= width - 3 - let w = w + a - let res = res.c - endif - endfor - let res = res.'..' - let w = w + 2 - let res = res.strcharpart(a:line, w) - endif - else - let first = strcharpart(a:line, 0, a:position) - let res = first.text.strcharpart(a:line, a:position + strwidth(text)) - endif - return res -endfunction - -" Return new dict with keys removed -function! coc#helper#dict_omit(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 diff --git a/pack/acp/opt/coc.nvim/autoload/coc/list.vim b/pack/acp/opt/coc.nvim/autoload/coc/list.vim deleted file mode 100644 index 33eb067..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/list.vim +++ /dev/null @@ -1,292 +0,0 @@ -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 - -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 -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) - if a:append - silent call append(line('$'), a:lines) - else - silent call append(0, a:lines) - if exists('*deletebufline') - call deletebufline('%', len(a:lines) + 1, '$') - else - let n = len(a:lines) + 1 - let saved_reg = @" - silent execute n.',$d' - let @" = saved_reg - endif - endif -endfunction - -function! coc#list#options(...) - let list = ['--top', '--tab', '--normal', '--no-sort', '--input', '--strict', - \ '--regex', '--interactive', '--number-select', '--auto-preview', - \ '--ignore-case', '--no-quit', '--first'] - if get(g:, 'coc_enabled', 0) - let names = coc#rpc#request('listNames', []) - call extend(list, names) - endif - return join(list, "\n") -endfunction - -function! coc#list#names(...) abort - let names = coc#rpc#request('listNames', []) - 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, '') -endfunction - -function! coc#list#create(position, height, name, numberSelect) - if a:position ==# 'tab' - execute 'silent tabe list:///'.a:name - else - execute 'silent keepalt '.(a:position ==# 'top' ? '' : 'botright').a:height.'sp list:///'.a:name - execute 'resize '.a:height - endif - if a:numberSelect - setl norelativenumber - setl number - else - setl nonumber - setl norelativenumber - setl signcolumn=yes - endif - return [bufnr('%'), win_getid()] -endfunction - -" close list windows -function! coc#list#clean_up() abort - for i in range(1, winnr('$')) - let bufname = bufname(winbufnr(i)) - if bufname =~# 'list://' - execute i.'close!' - endif - endfor -endfunction - -function! coc#list#setup(source) - let b:list_status = {} - setl buftype=nofile nobuflisted nofen nowrap - setl norelativenumber bufhidden=wipe cursorline winfixheight - setl tabstop=1 nolist nocursorcolumn undolevels=-1 - setl signcolumn=auto - if has('nvim-0.5.0') || has('patch-8.1.0864') - setl scrolloff=0 - endif - if exists('&cursorlineopt') - setl cursorlineopt=both - endif - setl filetype=list - syntax case ignore - let source = a:source[8:] - let name = toupper(source[0]).source[1:] - execute 'syntax match Coc'.name.'Line /\v^.*$/' - nnoremap c -endfunction - -function! coc#list#has_preview() - for i in range(1, winnr('$')) - let preview = getwinvar(i, '&previewwindow') - if preview - return 1 - 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 - return - endif - execute 'resize '.a:height - if s:is_vim - redraw - endif -endfunction - -function! coc#list#set_height(height) abort - if winnr('$') == 1| return | endif - execute 'resize '.a:height -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim b/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim deleted file mode 100644 index 659cc11..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/rpc.vim +++ /dev/null @@ -1,127 +0,0 @@ -let s:is_win = has("win32") || has("win64") -let s:client = v:null -let s:name = 'coc' -let s:is_vim = !has('nvim') - -function! coc#rpc#start_server() - if get(g:, 'coc_node_env', '') ==# 'test' - " server already started - let s:client = coc#client#create(s:name, []) - let s:client['running'] = 1 - let s:client['chan_id'] = get(g:, 'coc_node_channel_id', 0) - call dictwatcheradd(g:, 'coc_node_channel_id', function('s:ChannelSet')) - return - endif - if empty(s:client) - let cmd = coc#util#job_command() - if empty(cmd) | return | endif - let $COC_VIMCONFIG = coc#util#get_config_home() - let $COC_DATA_HOME = coc#util#get_data_home() - let s:client = coc#client#create(s:name, cmd) - endif - if !coc#client#is_running('coc') - call s:client['start']() - endif -endfunction - -function! coc#rpc#started() abort - return !empty(s:client) -endfunction - -function! coc#rpc#ready() - if empty(s:client) || s:client['running'] == 0 - return 0 - endif - return 1 -endfunction - -function! s:ChannelSet(dict, key, val) - let chan_id = get(a:val, 'new', 0) - if empty(s:client) | return | endif - let s:client['running'] = 1 - let s:client['chan_id'] = chan_id - call dictwatcherdel(g:, 'coc_node_channel_id', function('s:ChannelSet')) -endfunction - -function! coc#rpc#kill() - let pid = get(g:, 'coc_process_pid', 0) - if !pid | return | endif - if s:is_win - call system('taskkill /PID '.pid) - else - call system('kill -9 '.pid) - endif -endfunction - -function! coc#rpc#get_errors() - return split(execute('messages'), "\n") -endfunction - -function! coc#rpc#stop() - if empty(s:client) - return - endif - try - if s:is_vim - call job_stop(ch_getjob(s:client['channel']), 'term') - else - call jobstop(s:client['chan_id']) - endif - catch /.*/ - " ignore - endtry -endfunction - -function! coc#rpc#restart() - if empty(s:client) - call coc#rpc#start_server() - else - call coc#float#close_all() - call coc#rpc#request('detach', []) - sleep 100m - let s:client['command'] = coc#util#job_command() - call coc#client#restart(s:name) - echohl MoreMsg | echom 'starting coc.nvim service' | echohl None - endif -endfunction - -function! coc#rpc#request(method, args) abort - if !coc#rpc#ready() - return '' - endif - return s:client['request'](a:method, a:args) -endfunction - -function! coc#rpc#notify(method, args) abort - if !coc#rpc#ready() - return '' - endif - call s:client['notify'](a:method, a:args) - return '' -endfunction - -function! coc#rpc#request_async(method, args, cb) abort - if !coc#rpc#ready() - return cb('coc.nvim service not started.') - endif - call s:client['request_async'](a:method, a:args, a:cb) -endfunction - -" receive async response -function! coc#rpc#async_response(id, resp, isErr) abort - if empty(s:client) - return - endif - call coc#client#on_response(s:name, a:id, a:resp, a:isErr) -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 args = a:args + [l:Cb] - try - call call(a:method, args) - catch /.*/ - call coc#rpc#notify('nvim_async_response_event', [a:id, v:exception]) - endtry -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/snippet.vim b/pack/acp/opt/coc.nvim/autoload/coc/snippet.vim deleted file mode 100644 index 59253f8..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/snippet.vim +++ /dev/null @@ -1,68 +0,0 @@ -let s:is_vim = !has('nvim') -let s:map_next = 1 - -function! coc#snippet#_select_mappings() - if !get(g:, 'coc_selectmode_mapping', 1) - return - endif - - redir => mappings - silent! smap - redir END - - for map in map(filter(split(mappings, '\n'), - \ "v:val !~# '^s' && v:val !~# '^\\a*\\s*<\\S\\+>'"), - \ "matchstr(v:val, '^\\a*\\s*\\zs\\S\\+')") - silent! execute 'sunmap' map - silent! execute 'sunmap ' map - endfor - - " same behaviour of ultisnips - snoremap c - snoremap c - snoremap c - snoremap "_c -endfunction - -function! coc#snippet#show_choices(lnum, col, len, values) abort - let m = mode() - call cursor(a:lnum, a:col + a:len) - if m !=# 'i' | startinsert | endif - call timer_start(20, { -> coc#_do_complete(a:col - 1, a:values, 0)}) - redraw -endfunction - -function! coc#snippet#enable() - if get(b:, 'coc_snippet_active', 0) == 1 - return - endif - let b:coc_snippet_active = 1 - silent! unlet g:coc_selected_text - call coc#snippet#_select_mappings() - let nextkey = get(g:, 'coc_snippet_next', '') - let prevkey = get(g:, 'coc_snippet_prev', '') - if maparg(nextkey, 'i') =~# 'expand-jump' - let s:map_next = 0 - endif - if s:map_next - execute 'inoremap '.nextkey." =coc#rpc#request('snippetNext', [])" - endif - execute 'inoremap '.prevkey." =coc#rpc#request('snippetPrev', [])" - execute 'snoremap '.prevkey." :call coc#rpc#request('snippetPrev', [])" - execute 'snoremap '.nextkey." :call coc#rpc#request('snippetNext', [])" -endfunction - -function! coc#snippet#disable() - if get(b:, 'coc_snippet_active', 0) == 0 - return - endif - let b:coc_snippet_active = 0 - let nextkey = get(g:, 'coc_snippet_next', '') - let prevkey = get(g:, 'coc_snippet_prev', '') - if s:map_next - silent! execute 'iunmap '.nextkey - endif - silent! execute 'iunmap '.prevkey - silent! execute 'sunmap '.prevkey - silent! execute 'sunmap '.nextkey -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/task.vim b/pack/acp/opt/coc.nvim/autoload/coc/task.vim deleted file mode 100644 index 2ef00a1..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/task.vim +++ /dev/null @@ -1,109 +0,0 @@ -" ============================================================================ -" Description: Manage long running tasks. -" Author: Qiming Zhao -" Licence: MIT licence -" Version: 0.1 -" Last Modified: April 08, 2019 -" ============================================================================ - -let s:is_vim = !has('nvim') -let s:running_task = {} - -function! coc#task#start(id, opts) - if coc#task#running(a:id) - call coc#task#stop(a:id) - endif - let cmd = [a:opts['cmd']] + get(a:opts, 'args', []) - let cwd = get(a:opts, 'cwd', getcwd()) - " cmd args cwd pty - if s:is_vim - let options = { - \ 'cwd': cwd, - \ 'err_mode': 'nl', - \ 'out_mode': 'nl', - \ '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)}, - \} - if has("patch-8.1.350") - let options['noblock'] = 1 - endif - if get(a:opts, 'pty', 0) - let options['pty'] = 1 - endif - let job = job_start(cmd, options) - let status = job_status(job) - if status !=# 'run' - echohl Error | echom 'Failed to start '.a:id.' task' | echohl None - return v:false - endif - let s:running_task[a:id] = job - 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_exit': {channel, code -> s:on_exit(a:id, code)}, - \ 'detach': get(a:opts, 'detach', 0), - \} - if get(a:opts, 'pty', 0) - let options['pty'] = 1 - endif - let chan_id = jobstart(cmd, options) - if chan_id <= 0 - echohl Error | echom 'Failed to start '.a:id.' task' | echohl None - return v:false - endif - let s:running_task[a:id] = chan_id - endif - return v:true -endfunction - -function! coc#task#stop(id) - let job = get(s:running_task, a:id, v:null) - if !job | return | endif - if s:is_vim - call job_stop(job, 'term') - else - call jobstop(job) - endif - sleep 50m - let running = coc#task#running(a:id) - if running - echohl Error | echom 'job '.a:id. ' stop failed.' | echohl None - endif -endfunction - -function! s:on_exit(id, code) abort - if get(g:, 'coc_vim_leaving', 0) | return | endif - if has_key(s:running_task, a:id) - call remove(s:running_task, a:id) - endif - call coc#rpc#notify('TaskExit', [a:id, a:code]) -endfunction - -function! s:on_stderr(id, msgs) - if get(g:, 'coc_vim_leaving', 0) | return | endif - if len(a:msgs) - call coc#rpc#notify('TaskStderr', [a:id, a:msgs]) - endif -endfunction - -function! s:on_stdout(id, msgs) - if len(a:msgs) - call coc#rpc#notify('TaskStdout', [a:id, a:msgs]) - endif -endfunction - -function! coc#task#running(id) - if !has_key(s:running_task, a:id) == 1 - return v:false - endif - let job = s:running_task[a:id] - if s:is_vim - let status = job_status(job) - return status ==# 'run' - endif - let [code] = jobwait([job], 10) - return code == -1 -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim b/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim deleted file mode 100644 index 24dc0b7..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/terminal.vim +++ /dev/null @@ -1,114 +0,0 @@ -let s:is_vim = !has('nvim') -let s:channel_map = {} -let s:is_win = has('win32') || has('win64') - -" start terminal, return [bufnr, pid] -function! coc#terminal#start(cmd, cwd, env) abort - if s:is_vim && !has('terminal') - throw 'terminal feature not supported by current vim.' - endif - let cwd = empty(a:cwd) ? getcwd() : a:cwd - execute 'belowright 8new +setl\ buftype=nofile' - setl winfixheight - setl norelativenumber - setl nonumber - setl bufhidden=hide - if exists('#User#CocTerminalOpen') - exe 'doautocmd User CocTerminalOpen' - endif - let bufnr = bufnr('%') - let env = {} - let original = {} - if !empty(a:env) - " use env option when possible - if s:is_vim - let env = copy(a:env) - else - for key in keys(a:env) - let original[key] = getenv(key) - call setenv(key, a:env[key]) - endfor - endif - endif - - function! s:OnExit(status) closure - if a:status == 0 - execute 'silent! bd! '.bufnr - endif - endfunction - - if has('nvim') - let job_id = termopen(a:cmd, { - \ 'cwd': cwd, - \ 'pty': 1, - \ 'on_exit': {job, status -> s:OnExit(status)}, - \ 'env': env, - \ }) - if !empty(original) - for key in keys(original) - call setenv(key, original[key]) - endfor - endif - if job_id == 0 - throw 'create terminal job failed' - endif - wincmd p - let s:channel_map[bufnr] = job_id - return [bufnr, jobpid(job_id)] - else - let cmd = s:is_win ? join(a:cmd, ' ') : a:cmd - let res = term_start(cmd, { - \ 'cwd': cwd, - \ 'term_kill': s:is_win ? 'kill' : 'term', - \ 'term_finish': 'close', - \ 'exit_cb': {job, status -> s:OnExit(status)}, - \ 'curwin': 1, - \ 'env': env, - \}) - if res == 0 - throw 'create terminal job failed' - endif - let job = term_getjob(bufnr) - let s:channel_map[bufnr] = job_getchannel(job) - wincmd p - return [bufnr, job_info(job).process] - endif -endfunction - -function! coc#terminal#send(bufnr, text, add_new_line) abort - let chan = get(s:channel_map, a:bufnr, v:null) - if empty(chan) | return| endif - if has('nvim') - let lines = split(a:text, '\v\r?\n') - if a:add_new_line && !empty(lines[len(lines) - 1]) - if s:is_win - call add(lines, "\r\n") - else - call add(lines, '') - endif - endif - call chansend(chan, lines) - let winnr = bufwinnr(a:bufnr) - if winnr != -1 - exe 'noa '.winnr.'wincmd w' - exe 'noa normal! G' - exe 'noa '.wincmd p - endif - else - if !a:add_new_line - call ch_sendraw(chan, a:text) - else - call ch_sendraw(chan, a:text.(s:is_win ? "\r\n" : "\n")) - endif - endif -endfunction - -function! coc#terminal#close(bufnr) abort - if has('nvim') - let job_id = get(s:channel_map, a:bufnr, 0) - if !empty(job_id) - silent! call chanclose(job_id) - endif - endif - exe 'silent! bd! '.a:bufnr -endfunction diff --git a/pack/acp/opt/coc.nvim/autoload/coc/util.vim b/pack/acp/opt/coc.nvim/autoload/coc/util.vim deleted file mode 100644 index 6b98f8b..0000000 --- a/pack/acp/opt/coc.nvim/autoload/coc/util.vim +++ /dev/null @@ -1,1117 +0,0 @@ -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:activate = "" -let s:quit = "" -if has("gui_macvim") && has('gui_running') - let s:app = "MacVim" -elseif $TERM_PROGRAM ==# "Apple_Terminal" - let s:app = "Terminal" -elseif $TERM_PROGRAM ==# "iTerm.app" - let s:app = "iTerm2" -elseif has('mac') - let s:app = "System Events" - let s:quit = "quit" - let s:activate = 'activate' -endif - -function! coc#util#has_preview() - for i in range(1, winnr('$')) - if getwinvar(i, '&previewwindow') - return i - endif - endfor - 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 '' -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)] -endfunction - -function! coc#util#path_replace_patterns() abort - if has('win32unix') && exists('g:coc_cygqwin_path_prefixes') - echohl WarningMsg - echon 'g:coc_cygqwin_path_prefixes is deprecated, use g:coc_uri_prefix_replace_patterns instead' - echohl None - return g:coc_cygqwin_path_prefixes - endif - if exists('g:coc_uri_prefix_replace_patterns') - return g:coc_uri_prefix_replace_patterns - endif - return v:null -endfunction - -function! coc#util#version() - if s:is_vim - return string(v:versionlong) - endif - let c = execute('silent version') - let lines = split(matchstr(c, 'NVIM v\zs[^\n-]*')) - return lines[0] -endfunction - -function! coc#util#check_refresh(bufnr) - if !bufloaded(a:bufnr) - return 0 - endif - if getbufvar(a:bufnr, 'coc_diagnostic_disable', 0) - return 0 - endif - if get(g: , 'EasyMotion_loaded', 0) - return EasyMotion#is_active() != 1 - endif - return 1 -endfunction - -function! coc#util#open_file(cmd, file) - let file = fnameescape(a:file) - execute a:cmd .' '.file -endfunction - -function! coc#util#remote_fns(name) - let fns = ['init', 'complete', 'should_complete', 'refresh', 'get_startcol', 'on_complete', 'on_enter'] - let res = [] - for fn in fns - if exists('*coc#source#'.a:name.'#'.fn) - call add(res, fn) - endif - endfor - return res -endfunction - -function! coc#util#job_command() - if (has_key(g:, 'coc_node_path')) - let node = expand(g:coc_node_path) - else - let node = $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH - endif - if !executable(node) - 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'] - endif -endfunction - -function! coc#util#echo_hover(msg) - echohl MoreMsg - echo a:msg - echohl None - let g:coc_last_hover_message = a:msg -endfunction - -function! coc#util#execute(cmd) - silent exe a:cmd - if &filetype ==# '' - filetype detect - endif - if s:is_vim - redraw! - endif -endfunction - -function! coc#util#jump(cmd, filepath, ...) abort - silent! normal! m' - 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 !empty(get(a:, 1, [])) - let line = getline(a:1[0] + 1) - " TODO need to use utf16 here - let col = byteidx(line, a:1[1]) + 1 - if col == 0 - let col = 999 - endif - call cursor(a:1[0] + 1, col) - endif - if &filetype ==# '' - filetype detect - endif - if s:is_vim - redraw - endif -endfunction - -function! coc#util#jumpTo(line, character) abort - let content = getline(a:line + 1) - let pre = strcharpart(content, 0, a:character) - let col = strlen(pre) + 1 - call cursor(a:line + 1, col) -endfunction - -function! coc#util#echo_messages(hl, msgs) - if a:hl !~# 'Error' && (mode() !~# '\v^(i|n)$') - return - endif - let msgs = filter(copy(a:msgs), '!empty(v:val)') - if empty(msgs) - return - endif - execute 'echohl '.a:hl - echom a:msgs[0] - redraw - echo join(msgs, "\n") - echohl None -endfunction - -function! coc#util#echo_lines(lines) - echo join(a:lines, "\n") -endfunction - -function! coc#util#timer(method, args) - call timer_start(0, { -> s:Call(a:method, a:args)}) -endfunction - -function! s:Call(method, args) - try - call call(a:method, a:args) - redraw - catch /.*/ - return 0 - endtry -endfunction - -function! coc#util#get_bufoptions(bufnr) abort - if !bufloaded(a:bufnr) | return v:null | endif - let bufname = bufname(a:bufnr) - let buftype = getbufvar(a:bufnr, '&buftype') - let previewwindow = 0 - let winid = bufwinid(a:bufnr) - if winid != -1 - let previewwindow = getwinvar(winid, '&previewwindow', 0) - endif - let size = -1 - if bufnr('%') == a:bufnr - let size = line2byte(line("$") + 1) - elseif !empty(bufname) - let size = getfsize(bufname) - 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'), - \ 'filetype': getbufvar(a:bufnr, '&filetype'), - \ 'iskeyword': getbufvar(a:bufnr, '&iskeyword'), - \ 'changedtick': getbufvar(a:bufnr, 'changedtick'), - \} -endfunction - -function! s:variables(bufnr) abort - let info = getbufinfo({'bufnr':a:bufnr, 'variables': 1}) - let variables = copy(info[0]['variables']) - for key in keys(variables) - if key !~# '\v^coc' - unlet variables[key] - endif - endfor - return variables -endfunction - -function! coc#util#root_patterns() abort - return coc#rpc#request('rootPatterns', [bufnr('%')]) -endfunction - -function! coc#util#get_config(key) abort - return coc#rpc#request('getConfig', [a:key]) -endfunction - -function! coc#util#on_error(msg) abort - echohl Error | echom '[coc.nvim] '.a:msg | echohl None -endfunction - -function! coc#util#preview_info(info, filetype, ...) abort - pclose - keepalt new +setlocal\ previewwindow|setlocal\ buftype=nofile|setlocal\ noswapfile|setlocal\ wrap [Document] - setl bufhidden=wipe - setl nobuflisted - setl nospell - exe 'setl filetype='.a:filetype - setl conceallevel=2 - setl nofoldenable - for command in a:000 - execute command - endfor - let lines = a:info - call append(0, lines) - exe "normal! z" . len(lines) . "\" - exe "normal! gg" - wincmd p -endfunction - -function! coc#util#get_config_home() - if !empty(get(g:, 'coc_config_home', '')) - return resolve(expand(g:coc_config_home)) - endif - if exists('$VIMCONFIG') - return resolve($VIMCONFIG) - endif - if has('nvim') - if exists('$XDG_CONFIG_HOME') - return resolve($XDG_CONFIG_HOME."/nvim") - endif - if s:is_win - return resolve($HOME.'/AppData/Local/nvim') - endif - return resolve($HOME.'/.config/nvim') - else - if s:is_win - return resolve($HOME."/vimfiles") - endif - return resolve($HOME.'/.vim') - endif -endfunction - -function! coc#util#get_data_home() - if !empty(get(g:, 'coc_data_home', '')) - let dir = resolve(expand(g:coc_data_home)) - else - if exists('$XDG_CONFIG_HOME') - let dir = resolve($XDG_CONFIG_HOME."/coc") - else - if s:is_win - let dir = resolve(expand('~/AppData/Local/coc')) - else - let dir = resolve(expand('~/.config/coc')) - endif - endif - endif - if !isdirectory(dir) - echohl MoreMsg | echom '[coc.nvim] creating data directory: '.dir | echohl None - call mkdir(dir, "p", 0755) - endif - return dir -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] -endfunction - -function! coc#util#move_cursor(delta) - let pos = getcurpos() - call cursor(pos[1], pos[2] + a: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") - return { - \ 'word': matchstr(line[l:start : ], '^\k\+'), - \ 'input': empty(input) ? '' : input, - \ 'line': line, - \ 'filetype': &filetype, - \ 'filepath': expand('%:p'), - \ 'bufnr': bufnr('%'), - \ 'linenr': pos[1], - \ 'colnr' : pos[2], - \ 'col': l:start, - \ 'synname': synname, - \ 'changedtick': b:changedtick, - \ 'blacklist': blacklist, - \} -endfunction - -function! coc#util#with_callback(method, args, cb) - function! s:Cb() closure - try - let res = call(a:method, a:args) - call a:cb(v:null, res) - catch /.*/ - call a:cb(v:exception) - endtry - endfunction - let timeout = s:is_vim ? 10 : 0 - call timer_start(timeout, {-> s:Cb() }) -endfunction - -function! coc#util#quickpick(title, items, cb) abort - if exists('*popup_menu') - function! s:QuickpickHandler(id, result) closure - call a:cb(v:null, a:result) - endfunction - function! s:QuickpickFilter(id, key) closure - for i in range(1, len(a:items)) - if a:key == string(i) - call popup_close(a:id, i) - return 1 - endif - endfor - " No shortcut, pass to generic filter - return popup_filter_menu(a:id, a:key) - endfunction - try - call popup_menu(a:items, { - \ 'title': a:title, - \ 'filter': function('s:QuickpickFilter'), - \ 'callback': function('s:QuickpickHandler'), - \ }) - catch /.*/ - call a:cb(v:exception) - endtry - else - let res = inputlist([a:title] + a:items) - call a:cb(v:null, res) - 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 - -function! coc#util#echo_signatures(signatures) abort - if pumvisible() | return | endif - echo "" - for i in range(len(a:signatures)) - call s:echo_signature(a:signatures[i]) - if i != len(a:signatures) - 1 - echon "\n" - endif - endfor -endfunction - -function! s:echo_signature(parts) - for part in a:parts - let hl = get(part, 'type', 'Normal') - let text = get(part, 'text', '') - if !empty(text) - execute 'echohl '.hl - execute "echon '".substitute(text, "'", "''", 'g')."'" - echohl None - endif - endfor -endfunction - -function! coc#util#unplace_signs(bufnr, sign_ids) - if !bufloaded(a:bufnr) | return | endif - for id in a:sign_ids - execute 'silent! sign unplace '.id.' buffer='.a:bufnr - endfor -endfunction - -function! coc#util#setline(lnum, line) - keepjumps call setline(a:lnum, a:line) -endfunction - -" cmd, cwd -function! coc#util#open_terminal(opts) abort - if s:is_vim && !exists('*term_start') - echohl WarningMsg | echon "Your vim doesn't have terminal support!" | echohl None - return - endif - if get(a:opts, 'position', 'bottom') ==# 'bottom' - let p = '5new' - else - let p = 'vnew' - endif - execute 'belowright '.p.' +setl\ buftype=nofile ' - setl buftype=nofile - setl winfixheight - setl norelativenumber - setl nonumber - setl bufhidden=wipe - let cmd = get(a:opts, 'cmd', '') - let autoclose = get(a:opts, 'autoclose', 1) - if empty(cmd) - throw 'command required!' - endif - let cwd = get(a:opts, 'cwd', getcwd()) - let keepfocus = get(a:opts, 'keepfocus', 0) - let bufnr = bufnr('%') - let Callback = get(a:opts, 'Callback', v:null) - - function! s:OnExit(status) closure - let content = join(getbufline(bufnr, 1, '$'), "\n") - if a:status == 0 && autoclose == 1 - execute 'silent! bd! '.bufnr - endif - if !empty(Callback) - call call(Callback, [a:status, bufnr, content]) - endif - endfunction - - if has('nvim') - call termopen(cmd, { - \ 'cwd': cwd, - \ 'on_exit': {job, status -> s:OnExit(status)}, - \}) - else - if s:is_win - let cmd = 'cmd.exe /C "'.cmd.'"' - endif - call term_start(cmd, { - \ 'cwd': cwd, - \ 'exit_cb': {job, status -> s:OnExit(status)}, - \ 'curwin': 1, - \}) - endif - if keepfocus - wincmd p - endif - return bufnr -endfunction - -" run command in terminal -function! coc#util#run_terminal(opts, cb) - let cmd = get(a:opts, 'cmd', '') - if empty(cmd) - return a:cb('command required for terminal') - endif - let opts = { - \ 'cmd': cmd, - \ 'cwd': get(a:opts, 'cwd', getcwd()), - \ 'keepfocus': get(a:opts, 'keepfocus', 0), - \ 'Callback': {status, bufnr, content -> a:cb(v:null, {'success': status == 0 ? v:true : v:false, 'bufnr': bufnr, 'content': content})} - \} - call coc#util#open_terminal(opts) -endfunction - -function! coc#util#getpid() - if !has('win32unix') - return getpid() - endif - let cmd = 'cat /proc/' . getpid() . '/winpid' - return substitute(system(cmd), '\v\n', '', 'gi') -endfunction - -function! coc#util#vim_info() - return { - \ '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(), - \ 'columns': &columns, - \ 'lines': &lines, - \ 'cmdheight': &cmdheight, - \ 'filetypeMap': get(g:, 'coc_filetype_map', {}), - \ 'version': coc#util#version(), - \ 'completeOpt': &completeopt, - \ 'pumevent': exists('##MenuPopupChanged') || exists('##CompleteChanged'), - \ 'isVim': has('nvim') ? v:false : v:true, - \ 'isCygwin': has('win32unix') ? v:true : v:false, - \ 'isMacvim': has('gui_macvim') ? v:true : v:false, - \ 'isiTerm': $TERM_PROGRAM ==# "iTerm.app", - \ 'colorscheme': get(g:, 'colors_name', ''), - \ 'workspaceFolders': get(g:, 'WorkspaceFolders', v:null), - \ 'background': &background, - \ 'runtimepath': &runtimepath, - \ 'locationlist': get(g:,'coc_enable_locationlist', 1), - \ 'progpath': v:progpath, - \ 'guicursor': &guicursor, - \ 'vimCommands': get(g:, 'coc_vim_commands', []), - \ 'textprop': has('textprop') && has('patch-8.1.1719') && !has('nvim') ? v:true : v:false, - \ 'disabledSources': get(g:, 'coc_sources_disable_map', {}), - \} -endfunction - -function! coc#util#highlight_options() - return { - \ 'colorscheme': get(g:, 'colors_name', ''), - \ 'background': &background, - \ 'runtimepath': &runtimepath, - \} -endfunction - -" used by vim -function! coc#util#get_content(bufnr) - if !bufloaded(a:bufnr) | return '' | endif - return { - \ 'content': join(getbufline(a:bufnr, 1, '$'), "\n"), - \ 'changedtick': getbufvar(a:bufnr, 'changedtick') - \ } -endfunction - -" used for TextChangedI with InsertCharPre -function! coc#util#get_changeinfo() - return { - \ 'lnum': line('.'), - \ 'line': getline('.'), - \ 'changedtick': b:changedtick, - \} -endfunction - -" show diff of current buffer -function! coc#util#diff_content(lines) abort - let tmpfile = tempname() - setl foldenable - call writefile(a:lines, tmpfile) - let ft = &filetype - diffthis - execute 'vs '.tmpfile - if !empty(ft) - execute 'setf ' . ft - endif - diffthis - setl foldenable -endfunction - -function! coc#util#clear_signs() - let buflist = filter(range(1, bufnr('$')), 'buflisted(v:val)') - for b in buflist - let signIds = [] - let lines = split(execute('sign place buffer='.b), "\n") - for line in lines - let ms = matchlist(line, 'id=\(\d\+\)\s\+name=Coc') - if len(ms) > 0 - call add(signIds, ms[1]) - endif - endfor - call coc#util#unplace_signs(b, signIds) - endfor -endfunction - -function! coc#util#open_url(url) - if has('mac') && executable('open') - call system('open '.a:url) - return - endif - if executable('xdg-open') - call system('xdg-open '.a:url) - return - endif - call system('cmd /c start "" /b '. substitute(a:url, '&', '^&', 'g')) - if v:shell_error - echohl Error | echom 'Failed to open '.a:url | echohl None - return - endif -endfunction - -function! coc#util#install() abort - call coc#util#open_terminal({ - \ 'cwd': s:root, - \ 'cmd': 'yarn install --frozen-lockfile', - \ 'autoclose': 0, - \ }) -endfunction - -function! coc#util#do_complete(name, opt, cb) abort - let handler = 'coc#source#'.a:name.'#complete' - let l:Cb = {res -> a:cb(v:null, res)} - let args = [a:opt, l:Cb] - call call(handler, args) -endfunction - -function! coc#util#extension_root() abort - if get(g:, 'coc_node_env', '') ==# 'test' - return s:root.'/src/__tests__/extensions' - endif - if !empty(get(g:, 'coc_extension_root', '')) - echohl Error | echon 'g:coc_extension_root not used any more, use g:coc_data_home instead' | echohl None - endif - return coc#util#get_data_home().'/extensions' -endfunction - -function! coc#util#update_extensions(...) abort - let async = get(a:, 1, 0) - if async - call coc#rpc#notify('updateExtensions', []) - else - call coc#rpc#request('updateExtensions', [v:true]) - endif -endfunction - -function! coc#util#install_extension(args) abort - let names = filter(copy(a:args), 'v:val !~# "^-"') - let isRequest = index(a:args, '-sync') != -1 - if isRequest - call coc#rpc#request('installExtensions', names) - else - call coc#rpc#notify('installExtensions', names) - endif -endfunction - -function! coc#util#do_autocmd(name) abort - if exists('#User#'.a:name) - exe 'doautocmd User '.a:name - endif -endfunction - -function! coc#util#rebuild() - let dir = coc#util#extension_root() - if !isdirectory(dir) | return | endif - call coc#util#open_terminal({ - \ 'cwd': dir, - \ 'cmd': 'npm rebuild', - \ 'keepfocus': 1, - \}) -endfunction - -" content of first echo line -function! coc#util#echo_line() - let str = '' - let line = &lines - (&cmdheight - 1) - for i in range(1, &columns - 1) - let nr = screenchar(line, i) - let str = str . nr2char(nr) - endfor - return str -endfunction - -" [r, g, b] ['255', '255', '255'] -" return ['65535', '65535', '65535'] or return v:false to cancel -function! coc#util#pick_color(default_color) - if has('mac') - let default_color = map(a:default_color, {idx, val -> str2nr(val) * 65535 / 255 }) - " This is the AppleScript magic: - let s:ascrpt = ['-e "tell application \"' . s:app . '\""', - \ '-e "' . s:activate . '"', - \ "-e \"set AppleScript's text item delimiters to {\\\",\\\"}\"", - \ '-e "set theColor to (choose color default color {' . default_color[0] . ", " . default_color[1] . ", " . default_color[2] . '}) as text"', - \ '-e "' . s:quit . '"', - \ '-e "end tell"', - \ '-e "return theColor"'] - let res = trim(system("osascript " . join(s:ascrpt, ' ') . " 2>/dev/null")) - if empty(res) - return v:false - else - return split(trim(res), ',') - endif - endif - - let hex_color = printf('#%02x%02x%02x', a:default_color[0], a:default_color[1], a:default_color[2]) - - if has('unix') - if executable('zenity') - let res = trim(system('zenity --title="Select a color" --color-selection --color="' . hex_color . '" 2> /dev/null')) - if empty(res) - return v:false - else - " res format is rgb(255,255,255) - return map(split(res[4:-2], ','), {idx, val -> string(str2nr(trim(val)) * 65535 / 255)}) - endif - endif - endif - - let rgb = v:false - if !has('python') - echohl Error | echom 'python support required, checkout :echo has(''python'')' | echohl None - return - endif - try - execute 'py import gtk' - catch /.*/ - echohl Error | echom 'python gtk module not found' | echohl None - return - endtry -python << endpython - -import vim -import gtk, sys - -# message strings -wnd_title_insert = "Insert a color" - -csd = gtk.ColorSelectionDialog(wnd_title_insert) -cs = csd.colorsel - -cs.set_current_color(gtk.gdk.color_parse(vim.eval("hex_color"))) - -cs.set_current_alpha(65535) -cs.set_has_opacity_control(False) -# cs.set_has_palette(int(vim.eval("s:display_palette"))) - -if csd.run()==gtk.RESPONSE_OK: - c = cs.get_current_color() - s = [str(int(c.red)),',',str(int(c.green)),',',str(int(c.blue))] - thecolor = ''.join(s) - vim.command(":let rgb = split('%s',',')" % thecolor) - -csd.destroy() - -endpython - return rgb -endfunction - -function! coc#util#iterm_open(dir) - return s:osascript( - \ 'if application "iTerm2" is not running', - \ 'error', - \ 'end if') && s:osascript( - \ 'tell application "iTerm2"', - \ 'tell current window', - \ 'create tab with default profile', - \ 'tell current session', - \ 'write text "cd ' . a:dir . '"', - \ 'write text "clear"', - \ 'activate', - \ 'end tell', - \ 'end tell', - \ 'end tell') -endfunction - -function! s:osascript(...) abort - let args = join(map(copy(a:000), '" -e ".shellescape(v:val)'), '') - call s:system('osascript'. args) - return !v:shell_error -endfunction - -function! s:system(cmd) - let output = system(a:cmd) - if v:shell_error && output !=# "" - echohl Error | echom output | echohl None - return - endif - return output -endfunction - -function! coc#util#set_buf_var(bufnr, name, val) abort - if !bufloaded(a:bufnr) | return | endif - 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 - exe 'silent! nunmap '.key - endfor - endif -endfunction - -function! coc#util#open_files(files) - let bufnrs = [] - " added on latest vim8 - if exists('*bufadd') && exists('*bufload') - for file in a:files - if bufloaded(file) - call add(bufnrs, bufnr(file)) - else - let bufnr = bufadd(file) - call bufload(file) - call add(bufnrs, bufnr) - call setbufvar(bufnr, '&buflisted', 1) - endif - endfor - else - noa keepalt 1new +setl\ bufhidden=wipe - for file in a:files - execute 'noa edit +setl\ bufhidden=hide '.fnameescape(file) - if &filetype ==# '' - filetype detect - endif - call add(bufnrs, bufnr('%')) - endfor - noa close - endif - doautocmd BufEnter - return bufnrs -endfunction - -function! coc#util#refactor_foldlevel(lnum) abort - if a:lnum <= 2 | return 0 | endif - let line = getline(a:lnum) - if line =~# '^\%u3000\s*$' | return 0 | endif - return 1 -endfunction - -function! coc#util#get_pretext() abort - return strpart(getline('.'), 0, col('.') - 1) -endfunction - -function! coc#util#refactor_fold_text(lnum) abort - let range = '' - let info = get(b:line_infos, a:lnum, []) - if !empty(info) - let range = info[0].':'.info[1] - endif - return trim(getline(a:lnum)[3:]).' '.range -endfunction - -function! coc#util#set_buf_lines(bufnr, lines) abort - let res = setbufline(a:bufnr, 1, a:lines) - if res == 0 - call deletebufline(a:bufnr, len(a:lines) + 1, '$') - endif -endfunction - -" get tabsize & expandtab option -function! coc#util#get_format_opts(bufnr) abort - if a:bufnr && bufloaded(a:bufnr) - let tabsize = getbufvar(a:bufnr, '&shiftwidth') - if tabsize == 0 - let tabsize = getbufvar(a:bufnr, '&tabstop') - endif - return [tabsize, getbufvar(a:bufnr, '&expandtab')] - endif - let tabsize = &shiftwidth == 0 ? &tabstop : &shiftwidth - 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 -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 - endif -endfunction - -" Make sure window exists -function! coc#util#win_gotoid(winid) abort - noa let res = win_gotoid(a:winid) - if res == 0 - 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 deleted file mode 100644 index fe789b9..0000000 --- a/pack/acp/opt/coc.nvim/autoload/health/coc.vim +++ /dev/null @@ -1,97 +0,0 @@ -let s:root = expand(':h:h:h') - -function! s:checkEnvironment() abort - let valid = 1 - if !has('nvim-0.3.0') - let valid = 0 - call health#report_error('Neovim version not satisfied, 0.3.0 and above required') - endif - let node = get(g:, 'coc_node_path', $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH) - if !executable(node) - let valid = 0 - call health#report_error('Executable node.js not found, install node.js from http://nodejs.org/') - endif - let output = system(node . ' --version') - if v:shell_error && output !=# "" - let valid = 0 - call health#report_error(output) - endif - let ms = matchlist(output, 'v\(\d\+\).\(\d\+\).\(\d\+\)') - if empty(ms) - let valid = 0 - call health#report_error('Unable to detect version of node, make sure your node executable is http://nodejs.org/') - elseif str2nr(ms[1]) < 8 || (str2nr(ms[1]) == 8 && str2nr(ms[2]) < 10) - let valid = 0 - call health#report_error('Node.js version '.output.' < 8.10.0, please upgrade node.js') - elseif str2nr(ms[1]) < 10 || (str2nr(ms[1]) == 10 && str2nr(ms[2]) < 12) - let valid = 0 - call health#report_warn('Node.js version '.trim(output).' < 10.12.0, please upgrade node.js') - endif - if valid - call health#report_ok('Environment check passed') - endif - if has('pythonx') - try - silent pyx print("") - catch /.*/ - call health#report_warn('pyx command not work, some extensions may fail to work, checkout ":h pythonx"') - endtry - endif - return valid -endfunction - -function! s:checkCommand() - let file = s:root.'/bin/server.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 - 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 - endif -endfunction - -function! s:checkAutocmd() - let cmds = ['CursorHold', 'CursorHoldI', 'CursorMovedI', 'InsertCharPre', 'TextChangedI'] - for cmd in cmds - let lines = split(execute('verbose autocmd '.cmd), '\n') - let n = 0 - for line in lines - if line =~# 'CocAction(' && n < len(lines) - 1 - let next = lines[n + 1] - let ms = matchlist(next, 'Last set from \(.*\)') - if !empty(ms) - call health#report_warn('Use CocActionAsync to replace CocAction for better performance on '.cmd) - call health#report_warn('Checkout the file '.ms[1]) - endif - endif - let n = n + 1 - endfor - endfor -endfunction - -function! s:checkInitailize() abort - if coc#client#is_running('coc') - call health#report_ok('Service started') - return 1 - endif - call health#report_error('service could not be initialized', [ - \ 'Use command ":messages" to get error messages.', - \ 'Open a issue at https://github.com/neoclide/coc.nvim/issues for feedback.' - \]) - return 0 -endfunction - -function! health#coc#check() abort - call s:checkEnvironment() - call s:checkCommand() - call s:checkInitailize() - call s:checkAutocmd() -endfunction diff --git a/pack/acp/opt/coc.nvim/build/index.js b/pack/acp/opt/coc.nvim/build/index.js deleted file mode 100644 index 5356fce..0000000 --- a/pack/acp/opt/coc.nvim/build/index.js +++ /dev/null @@ -1,91426 +0,0 @@ -/******/ (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 = ` -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"; -/*! - * @description Recursive object extending - * @author Viacheslav Lotsmanov - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013-2018 Viacheslav Lotsmanov - * - * 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. - */ - - - -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. - */ -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]); - */ -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