robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local M ={} 2 3local http_methods ={ 4GET =true , 5POST =true , 6PUT =true , 7PATCH =true , 8HEAD =true , 9DELETE =true , 10} 11 12---@alias vim.net.request.ResponseFunc fun(err: string?, response: vim.net.request.Response?) 13---@alias vim.net.HttpMethod string "GET" | "POST" | "PUT" | "PATCH" | "HEAD" | "DELETE" 14 15---@class vim.net.request.Opts 16---@inlinedoc 17--- 18---Enables verbose output. 19---@field verbose? boolean 20--- 21---Number of retries on transient failures (default: 3). 22---@field retry? integer 23--- 24---Request body for POST/PUT/PATCH requests. 25---@field body? string 26--- 27---File path to save the response body to. 28---@field outpath? string 29--- 30---Buffer to save the response body to. 31---@field outbuf? integer 32--- 33---Custom headers to send with the request. Supports basic key/value headers and empty headers as 34---supported by curl. Does not support "@filename" style, internal header deletion ("Header:"). 35---@field headers? table<string, string> 36 37---@class vim.net.request.Response 38--- 39---The HTTP body of the request 40---@field body string 41 42--- Makes an HTTP request to the given URL, asynchronously passing the result to the specified 43--- `on_response`, `outpath` or `outbuf`. 44--- 45--- Examples: 46--- ```lua 47--- -- Write response body to file. 48--- vim.net.request('https://neovim.io/charter/', { 49--- outpath = 'vision.html', 50--- }) 51--- 52--- -- Process the response. 53--- vim.net.request( 54--- 'https://api.github.com/repos/neovim/neovim', 55--- {}, 56--- function (err, res) 57--- if err then return end 58--- local stars = vim.json.decode(res.body).stargazers_count 59--- vim.print(('Neovim currently has %d stars'):format(stars)) 60--- end 61--- ) 62--- 63--- -- Write to both file and current buffer, but cancel it. 64--- local job = vim.net.request('https://neovim.io/charter/', { 65--- outpath = 'vision.html', 66--- outbuf = 0, 67--- }) 68--- job:close() 69--- 70--- -- Add custom headers in the request. 71--- vim.net.request('https://neovim.io/charter/', { 72--- headers = { Authorization = 'Bearer XYZ' }, 73--- }) 74--- 75--- -- POST request with body. 76--- vim.net.request('POST', 'https://example.com/api', { 77--- body = '{"key": "value"}', 78--- headers = {['Content-Type'] = 'application/json' } 79--- }) 80--- ``` 81--- 82--- @param method vim.net.HttpMethod (default: GET) The HTTP method (GET, POST, PUT, PATCH, HEAD, DELETE). 83--- @param url string The URL for the request. 84--- @param opts? vim.net.request.Opts 85--- @param on_response? vim.net.request.ResponseFunc Callback invoked on request completion. 86--- @overload fun(url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc) 87--- @overload fun(method: vim.net.HttpMethod, url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc) 88--- @return { close: fun() } # Object with `close()` method which cancels the request. 89function M . request ( method , url , opts , on_response ) 90if type ( url ) ~= 'string' then 91on_response =opts --[[@as vim.net.request.ResponseFunc?]] 92opts =url --[[@as vim.net.request.Opts?]] 93url =method 94method ='GET' 95end 96opts =opts or {} 97 98vim . validate ( 'method' , method , function ( m ) 99return http_methods [ m ] == true 100end , 'method should be one of GET, POST, PUT, PATCH, HEAD, DELETE' ) 101vim . validate ( 'url' , url , 'string' ) 102vim . validate ( 'opts' , opts , 'table' , true ) 103vim . validate ( 'opts.headers' , opts . headers , 'table' , true ) 104vim . validate ( 'opts.body' , opts . body , function ( b ) 105return ( b == nil and true ) or ( type ( b ) == 'string' and not b : match ( '^@' )) 106end , true , 'body should be string and not start with @' ) 107vim . validate ( 'on_response' , on_response , 'function' , true ) 108---@cast on_response vim.net.request.ResponseFunc? 109 110local retry =opts . retry or 3 111 112-- Build curl command 113local args ={ 'curl' } 114if opts . verbose then 115table . insert ( args , '--verbose' ) 116else 117vim . list_extend ( args , { '--silent' , '--show-error' , '--fail' } ) 118end 119vim . list_extend ( args , { '--location' , '--retry' , tostring ( retry ) } ) 120 121if opts . outpath then 122vim . list_extend ( args , { '--output' , opts . outpath } ) 123end 124 125-- curl -X HEAD does not work and advises to use --head instead 126vim . list_extend ( args , method == 'HEAD' and { '--head' } or { '--request' , method } ) 127 128if vim . list_contains ( { 'POST' , 'PUT' , 'PATCH' } , method ) and opts . body then 129vim . list_extend ( args , { '--data-binary' , '@-' } ) 130end 131 132if opts . headers then 133for key , value in pairs ( opts . headers ) do 134if type ( key ) ~= 'string' or type ( value ) ~= 'string' then 135error ( 'headers keys and values must be strings' ) 136end 137 138if key : match ( ':$' ) or key : match ( ';$' ) or key : match ( '^@' ) then 139error ( 'header keys must not start with @ or end with : and ;' ) 140end 141 142if value == '' then 143vim . list_extend ( args , { '--header' , key .. ';' } ) 144else 145vim . list_extend ( args , { '--header' , key .. ': ' .. value } ) 146end 147end 148end 149 150table . insert ( args , url ) 151 152local system_opts =opts . body and { stdin =opts . body } or {} 153local job =vim . system ( args , system_opts , function ( res ) 154--- @cast res.stdout -? 155---@type string?, vim.net.request.Response? 156local err , response =nil , nil 157if res . signal ~= 0 then 158err =( 'Request killed with signal %d' ): format ( res . signal ) 159elseif res . code ~= 0 then 160err =res . stderr ~= '' and res . stderr or ( 'Request failed with exit code %d' ): format ( res . code ) 161else 162if on_response then 163response ={ body =res . stdout or '' } 164end 165end 166 167-- nvim_buf_is_loaded and nvim_buf_set_lines are not allowed in fast context 168vim . schedule ( function () 169if res . code == 0 and opts . outbuf and vim . api . nvim_buf_is_loaded ( opts . outbuf ) then 170local lines =vim . split ( res . stdout , '\n' , { plain =true } ) 171vim . api . nvim_buf_set_lines ( opts . outbuf , 0 , - 1 , true , lines ) 172end 173end ) 174 175if on_response then 176on_response ( err , response ) 177end 178end ) 179 180return { 181close =function () 182job : kill ( 'sigint' ) 183end , 184} 185end 186 187return M