# frozen_string_literal: true
# Author:: Akira Yamada <akira@ruby-lang.org>
# You can redistribute it and/or modify it under the same term as Ruby.
# See URI for general documentation
require_relative "rfc2396_parser"
require_relative "rfc3986_parser"
RFC3986_PARSER = RFC3986_Parser.new
DEFAULT_PARSER = Parser.new
DEFAULT_PARSER.pattern.each_pair do |sym, str|
unless REGEXP::PATTERN.const_defined?(sym)
REGEXP::PATTERN.const_set(sym, str)
DEFAULT_PARSER.regexp.each_pair do |sym, str|
def make_components_hash(klass, array_hash)
if array_hash.kind_of?(Array) &&
array_hash.size == klass.component.size - 1
klass.component[1..-1].each_index do |i|
tmp[klass.component[i + 1]] = array_hash[i].clone
tmp[klass.component[i + 1]] = array_hash[i]
elsif array_hash.kind_of?(Hash)
array_hash.each do |key, value|
"expected Array of or Hash of components of #{klass} (#{klass.component[1..-1].join(', ')})"
tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
module_function :make_components_hash
# Module for escaping unsafe characters with codes.
# URI.escape(str [, unsafe])
# Regexp that matches all symbols that must be replaced with codes.
# By default uses <tt>UNSAFE</tt>.
# When this argument is a String, it represents a character set.
# Escapes the string, replacing all unsafe characters with codes.
# This method is obsolete and should not be used. Instead, use
# CGI.escape, URI.encode_www_form or URI.encode_www_form_component
# depending on your specific use case.
# enc_uri = URI.escape("http://example.com/?a=\11\15")
# # => "http://example.com/?a=%09%0D"
# # => "http://example.com/?a=\t\r"
# URI.escape("@?@!", "!?")
warn "URI.escape is obsolete", uplevel: 1
DEFAULT_PARSER.escape(*arg)
# This method is obsolete and should not be used. Instead, use
# CGI.unescape, URI.decode_www_form or URI.decode_www_form_component
# depending on your specific use case.
# enc_uri = URI.escape("http://example.com/?a=\11\15")
# # => "http://example.com/?a=%09%0D"
# # => "http://example.com/?a=\t\r"
warn "URI.unescape is obsolete", uplevel: 1
DEFAULT_PARSER.unescape(*arg)
# Returns a Hash of the defined schemes.
# Base class for all URI exceptions.
class Error < StandardError; end
class InvalidURIError < Error; end
class InvalidComponentError < Error; end
# URI is valid, bad usage is not.
class BadURIError < Error; end
# Splits the string on following parts and returns array with result:
# URI.split("http://www.ruby-lang.org/")
# # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
RFC3986_PARSER.split(uri)
# Creates one of the URI's subclasses instance from the string.
# Raised if URI given is not a correct one.
# uri = URI.parse("http://www.ruby-lang.org/")
# # => #<URI::HTTP http://www.ruby-lang.org/>
# # => "www.ruby-lang.org"
# It's recommended to first ::escape the provided +uri_str+ if there are any
# invalid URI characters.
RFC3986_PARSER.parse(uri)
# URI::join(str[, str, ...])
# String(s) to work with, will be converted to RFC3986 URIs before merging.
# URI.join("http://example.com/","main.rbx")
# # => #<URI::HTTP http://example.com/main.rbx>
# URI.join('http://example.com', 'foo')
# # => #<URI::HTTP http://example.com/foo>
# URI.join('http://example.com', '/foo', '/bar')
# # => #<URI::HTTP http://example.com/bar>
# URI.join('http://example.com', '/foo', 'bar')
# # => #<URI::HTTP http://example.com/bar>
# URI.join('http://example.com', '/foo/', 'bar')
# # => #<URI::HTTP http://example.com/foo/bar>
RFC3986_PARSER.join(*str)
# URI::extract(str[, schemes][,&blk])
# String to extract URIs from.
# Limit URI matching to specific schemes.
# Extracts URIs from a string. If block given, iterates through all matched URIs.
# Returns nil if block given or array with matches.
# URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# # => ["http://foo.example.com/bla", "mailto:test@example.com"]
def self.extract(str, schemes = nil, &block)
warn "URI.extract is obsolete", uplevel: 1 if $VERBOSE
DEFAULT_PARSER.extract(str, schemes, &block)
# URI::regexp([match_schemes])
# Array of schemes. If given, resulting regexp matches to URIs
# whose scheme is one of the match_schemes.
# Returns a Regexp object which matches to URI-like strings.
# The Regexp object returned by this method includes arbitrary
# number of capture group (parentheses). Never rely on it's number.
# # extract first URI from html_string
# html_string.slice(URI.regexp)
# html_string.sub(URI.regexp(['ftp']), '')
# # You should not rely on the number of parentheses
# html_string.scan(URI.regexp) do |*matches|
def self.regexp(schemes = nil)
warn "URI.regexp is obsolete", uplevel: 1 if $VERBOSE
DEFAULT_PARSER.make_regexp(schemes)
TBLENCWWWCOMP_ = {} # :nodoc:
TBLENCWWWCOMP_[-i.chr] = -('%%%02X' % i)
TBLENCWWWCOMP_[' '] = '+'
TBLDECWWWCOMP_ = {} # :nodoc:
TBLDECWWWCOMP_[-('%%%X%X' % [h, l])] = -i.chr
TBLDECWWWCOMP_[-('%%%x%X' % [h, l])] = -i.chr
TBLDECWWWCOMP_[-('%%%X%x' % [h, l])] = -i.chr
TBLDECWWWCOMP_[-('%%%x%x' % [h, l])] = -i.chr
TBLDECWWWCOMP_['+'] = ' '
# Encodes given +str+ to URL-encoded form data.
# This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
# (ASCII space) to + and converts others to %XX.
# If +enc+ is given, convert +str+ to the encoding before percent encoding.
# This is an implementation of
# http://www.w3.org/TR/2013/CR-html5-20130806/forms.html#url-encoded-form-data.
# See URI.decode_www_form_component, URI.encode_www_form.
def self.encode_www_form_component(str, enc=nil)
if str.encoding != Encoding::ASCII_8BIT
if enc && enc != Encoding::ASCII_8BIT
str.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
str.encode!(enc, fallback: ->(x){"&##{x.ord};"})
str.force_encoding(Encoding::ASCII_8BIT)
str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
str.force_encoding(Encoding::US_ASCII)
# Decodes given +str+ of URL-encoded form data.
# See URI.encode_www_form_component, URI.decode_www_form.
def self.decode_www_form_component(str, enc=Encoding::UTF_8)
raise ArgumentError, "invalid %-encoding (#{str})" if /%(?!\h\h)/ =~ str
str.b.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
# Generates URL-encoded form data from given +enum+.
# This generates application/x-www-form-urlencoded data defined in HTML5
# from given an Enumerable object.
# This internally uses URI.encode_www_form_component(str).
# This method doesn't convert the encoding of given items, so convert them
# before calling this method if you want to send data as other than original
# encoding or mixed encoding data. (Strings which are encoded in an HTML5
# ASCII incompatible encoding are converted to UTF-8.)
# This method doesn't handle files. When you send a file, use
# This refers http://url.spec.whatwg.org/#concept-urlencoded-serializer
# URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
# URI.encode_www_form("q" => "ruby", "lang" => "en")
# URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
# #=> "q=ruby&q=perl&lang=en"
# URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
# #=> "q=ruby&q=perl&lang=en"
# See URI.encode_www_form_component, URI.decode_www_form.
def self.encode_www_form(enum, enc=nil)
encode_www_form_component(k, enc)
elsif v.respond_to?(:to_ary)
str = encode_www_form_component(k, enc)
str << encode_www_form_component(w, enc)
str = encode_www_form_component(k, enc)
str << encode_www_form_component(v, enc)
# Decodes URL-encoded form data from given +str+.
# This decodes application/x-www-form-urlencoded data
# and returns an array of key-value arrays.
# This refers http://url.spec.whatwg.org/#concept-urlencoded-parser,
# so this supports only &-separator, and doesn't support ;-separator.
# ary = URI.decode_www_form("a=1&a=2&b=3")
# ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
# ary.assoc('a').last #=> '1'
# ary.assoc('b').last #=> '3'
# ary.rassoc('a').last #=> '2'
# Hash[ary] #=> {"a"=>"2", "b"=>"3"}
# See URI.decode_www_form_component, URI.encode_www_form.
def self.decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
raise ArgumentError, "the input of #{self.name}.#{__method__} must be ASCII only string" unless str.ascii_only?
str.b.each_line(separator) do |string|
key, sep, val = string.partition('=')
if use__charset_ and key == '_charset_' and e = get_encoding(val)
key.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
val.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
=begin command for WEB_ENCODINGS_
curl https://encoding.spec.whatwg.org/encodings.json|
"shift_jis"=>"Windows-31J",
"iso-2022-jp"=>"cp50221",