deepl-rb 3.10.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +1 -1
  3. data/CHANGELOG.md +313 -1
  4. data/README.md +225 -309
  5. data/Rakefile +17 -8
  6. data/VERSION +1 -1
  7. data/deepl-rb.gemspec +73 -86
  8. data/lib/deepl/admin_client.rb +39 -14
  9. data/lib/deepl/api.rb +3 -17
  10. data/lib/deepl/app_info.rb +0 -1
  11. data/lib/deepl/client.rb +399 -84
  12. data/lib/deepl/configuration.rb +19 -70
  13. data/lib/deepl/exceptions/authorization_failed.rb +1 -1
  14. data/lib/deepl/exceptions/connection_error.rb +10 -7
  15. data/lib/deepl/exceptions/limit_exceeded.rb +1 -1
  16. data/lib/deepl/exceptions/quota_exceeded.rb +1 -1
  17. data/lib/deepl/exceptions/request_entity_too_large.rb +1 -2
  18. data/lib/deepl/exceptions/request_error.rb +7 -0
  19. data/lib/deepl/exceptions/server_error.rb +2 -1
  20. data/lib/deepl/exceptions/translation_memory_job_error.rb +32 -0
  21. data/lib/deepl/exceptions/validation_error.rb +3 -2
  22. data/lib/deepl/requests/base.rb +129 -51
  23. data/lib/deepl/requests/correct.rb +2 -8
  24. data/lib/deepl/requests/document/upload.rb +29 -26
  25. data/lib/deepl/requests/glossary/base.rb +30 -0
  26. data/lib/deepl/requests/glossary/create.rb +18 -22
  27. data/lib/deepl/requests/glossary/destroy.rb +4 -16
  28. data/lib/deepl/requests/glossary/entries.rb +6 -14
  29. data/lib/deepl/requests/glossary/find.rb +3 -13
  30. data/lib/deepl/requests/glossary/language_pairs.rb +2 -2
  31. data/lib/deepl/requests/glossary/list.rb +2 -2
  32. data/lib/deepl/requests/languages.rb +6 -11
  33. data/lib/deepl/requests/languages_for_resource.rb +2 -0
  34. data/lib/deepl/requests/multilingual_glossary/create.rb +8 -0
  35. data/lib/deepl/requests/multilingual_glossary/destroy_dictionary.rb +4 -0
  36. data/lib/deepl/requests/multilingual_glossary/entries.rb +5 -3
  37. data/lib/deepl/requests/multilingual_glossary/helpers.rb +22 -14
  38. data/lib/deepl/requests/rephrase.rb +3 -1
  39. data/lib/deepl/requests/spoken_terms/create.rb +5 -0
  40. data/lib/deepl/requests/spoken_terms/destroy_term_list.rb +1 -0
  41. data/lib/deepl/requests/spoken_terms/entries.rb +1 -0
  42. data/lib/deepl/requests/spoken_terms/helpers.rb +9 -2
  43. data/lib/deepl/requests/style_profile/create.rb +5 -0
  44. data/lib/deepl/requests/style_profile/list.rb +2 -2
  45. data/lib/deepl/requests/style_rule/create.rb +25 -1
  46. data/lib/deepl/requests/style_rule/create_custom_instruction.rb +7 -0
  47. data/lib/deepl/requests/style_rule/helpers.rb +13 -4
  48. data/lib/deepl/requests/style_rule/list.rb +2 -0
  49. data/lib/deepl/requests/style_rule/update.rb +1 -0
  50. data/lib/deepl/requests/style_rule/update_custom_instruction.rb +2 -0
  51. data/lib/deepl/requests/translate.rb +20 -36
  52. data/lib/deepl/requests/translation_memory/create_export.rb +6 -1
  53. data/lib/deepl/requests/translation_memory/create_import.rb +10 -0
  54. data/lib/deepl/requests/translation_memory/download_export.rb +0 -4
  55. data/lib/deepl/requests/translation_memory/list.rb +2 -2
  56. data/lib/deepl/requests/translation_memory/segments.rb +2 -2
  57. data/lib/deepl/requests/translation_memory/storage_base.rb +5 -9
  58. data/lib/deepl/requests/write_improvements.rb +7 -0
  59. data/lib/deepl/resources/document_handle.rb +1 -26
  60. data/lib/deepl/resources/document_translation_status.rb +0 -12
  61. data/lib/deepl/resources/language.rb +4 -10
  62. data/lib/deepl/resources/multilingual_glossary.rb +4 -4
  63. data/lib/deepl/resources/style_rule.rb +1 -23
  64. data/lib/deepl/resources/translation_memory_job.rb +3 -4
  65. data/lib/deepl/resources/usage.rb +5 -38
  66. data/lib/deepl/utils/client_builder.rb +44 -9
  67. data/lib/deepl/utils/glossary_entries.rb +30 -0
  68. data/lib/deepl/utils/http_client_builder.rb +50 -13
  69. data/lib/deepl/utils/output_path.rb +25 -0
  70. data/lib/deepl/utils/term_validator.rb +3 -3
  71. data/lib/deepl/utils/translation_memory_operations.rb +230 -0
  72. data/lib/deepl.rb +6 -171
  73. data/lib/http_client_options.rb +2 -2
  74. data/lib/version.rb +1 -1
  75. data/upgrading_to_v4.md +374 -0
  76. metadata +9 -50
  77. data/.gitlab-ci.yml +0 -197
  78. data/lib/deepl/deprecation.rb +0 -42
  79. data/lib/deepl/document_api.rb +0 -150
  80. data/lib/deepl/exceptions/not_supported.rb +0 -20
  81. data/lib/deepl/glossary_api.rb +0 -38
  82. data/lib/deepl/style_rule_api.rb +0 -72
  83. data/lib/deepl/translation_memory_api.rb +0 -389
  84. data/license_checker.sh +0 -8
  85. data/spec/fixtures.rb +0 -33
  86. data/spec/offline/admin_client_spec.rb +0 -551
  87. data/spec/offline/client_spec.rb +0 -273
  88. data/spec/offline/configuration_spec.rb +0 -164
  89. data/spec/offline/constants_spec.rb +0 -180
  90. data/spec/offline/correct_text_spec.rb +0 -50
  91. data/spec/offline/deprecation_spec.rb +0 -32
  92. data/spec/offline/errors_spec.rb +0 -92
  93. data/spec/offline/glossaries_spec.rb +0 -98
  94. data/spec/offline/http_client_spec.rb +0 -319
  95. data/spec/offline/languages_spec.rb +0 -155
  96. data/spec/offline/module_methods_spec.rb +0 -13
  97. data/spec/offline/multilingual_glossaries_spec.rb +0 -358
  98. data/spec/offline/offline_helper.rb +0 -71
  99. data/spec/offline/rephrase_text_spec.rb +0 -73
  100. data/spec/offline/spoken_terms_spec.rb +0 -215
  101. data/spec/offline/style_profiles_spec.rb +0 -266
  102. data/spec/offline/style_rules_spec.rb +0 -318
  103. data/spec/offline/translate_document_spec.rb +0 -606
  104. data/spec/offline/translate_text_spec.rb +0 -286
  105. data/spec/offline/translation_memories_client_spec.rb +0 -256
  106. data/spec/offline/translation_memories_spec.rb +0 -463
  107. data/spec/offline/usage_spec.rb +0 -151
  108. data/spec/real_api/admin_client_spec.rb +0 -77
  109. data/spec/real_api/correct_text_spec.rb +0 -20
  110. data/spec/real_api/glossaries_spec.rb +0 -28
  111. data/spec/real_api/languages_spec.rb +0 -27
  112. data/spec/real_api/multilingual_glossaries_spec.rb +0 -53
  113. data/spec/real_api/proxy_spec.rb +0 -41
  114. data/spec/real_api/real_api_helper.rb +0 -65
  115. data/spec/real_api/rephrase_text_spec.rb +0 -16
  116. data/spec/real_api/spoken_terms_spec.rb +0 -56
  117. data/spec/real_api/style_profiles_spec.rb +0 -46
  118. data/spec/real_api/style_rules_spec.rb +0 -46
  119. data/spec/real_api/translate_document_spec.rb +0 -18
  120. data/spec/real_api/translate_text_spec.rb +0 -16
  121. data/spec/real_api/translation_memories_spec.rb +0 -56
  122. data/spec/real_api/usage_spec.rb +0 -20
  123. data/spec/spec_helper.rb +0 -13
@@ -4,71 +4,23 @@
4
4
  # frozen_string_literal: true
5
5
 
6
6
  module DeepL
7
+ # The options of one DeepL::Client or DeepL::AdminClient, built by Utils::ClientBuilder.
8
+ # Nothing is read from the environment.
9
+ # @api private
7
10
  class Configuration
8
- ATTRIBUTES = %i[auth_key host logger max_doc_status_queries max_network_retries user_agent
9
- version headers timeout].freeze
11
+ ATTRIBUTES = %i[auth_key host logger max_network_retries user_agent headers timeout].freeze
10
12
 
11
- # max_doc_status_queries= is defined below, with its deprecation warning.
12
- attr_accessor(*(ATTRIBUTES - %i[max_doc_status_queries]))
13
- attr_reader :max_doc_status_queries
13
+ attr_reader(*ATTRIBUTES)
14
14
 
15
- DEEPL_SERVER_URL = 'https://api.deepl.com'
16
- DEEPL_SERVER_URL_FREE = 'https://api-free.deepl.com'
17
- # Net::HTTP's 60-second default, kept for the module-level API; 10 in the next major version.
18
- DEFAULT_TIMEOUT = 60.0
19
- private_constant :DEEPL_SERVER_URL, :DEEPL_SERVER_URL_FREE, :DEFAULT_TIMEOUT
20
-
21
- def initialize(data = {}, app_info_name = nil, app_info_version = nil, send_platform_info = true) # rubocop:disable all
22
- data.each { |key, value| send("#{key}=", value) }
23
- @auth_key ||= ENV.fetch('DEEPL_AUTH_KEY', nil)
24
- @host ||= ENV.fetch('DEEPL_SERVER_URL', nil)
25
- @version ||= 'v2'
26
- @user_agent ||= construct_user_agent(send_platform_info, app_info_name, app_info_version)
27
- @max_network_retries ||= 5
28
- @logger ||= nil
29
- @headers ||= {}
30
- @timeout ||= DEFAULT_TIMEOUT
31
- end
32
-
33
- # The host is resolved when it is read, so that an auth key set after the configuration was
34
- # created (e.g. in a +DeepL.configure+ block) still selects the Free API.
35
- def host
36
- return @host unless @host.nil?
37
-
38
- self.class.free_account_auth_key?(auth_key) ? DEEPL_SERVER_URL_FREE : DEEPL_SERVER_URL
39
- end
40
-
41
- ##
42
- # @deprecated Use the +timeout_s:+ of DeepL::Client#translate_document or
43
- # DeepL::Client#translate_document_wait_until_done instead.
44
- def max_doc_status_queries=(value)
45
- unless value.nil?
46
- DeepL::Deprecation.warn_once_at_caller(
47
- 'DeepL::Configuration#max_doc_status_queries=',
48
- '[DEPRECATION] DeepL::Configuration#max_doc_status_queries= is deprecated, use the ' \
49
- 'timeout_s: of DeepL::Client#translate_document instead.'
50
- )
51
- end
52
- @max_doc_status_queries = value
53
- end
54
-
55
- ##
56
- # @deprecated The API version is part of each endpoint; this setting will be removed in the
57
- # next major version.
58
- def version=(value)
59
- unless value.nil? || value == 'v2'
60
- DeepL::Deprecation.warn_once('DeepL::Configuration#version=',
61
- '[DEPRECATION] DeepL::Configuration#version= is deprecated ' \
62
- 'and will be removed in the next major version.')
63
- end
64
- @version = value
65
- end
66
-
67
- def validate!
68
- return unless auth_key.nil? || auth_key.to_s.strip.empty?
69
-
70
- raise Exceptions::Error,
71
- 'auth_key not provided'
15
+ def initialize(auth_key:, host:, max_network_retries:, timeout:, logger:, headers:, # rubocop:disable Metrics/ParameterLists
16
+ user_agent:, send_platform_info:, app_info:)
17
+ @auth_key = auth_key
18
+ @host = host
19
+ @max_network_retries = max_network_retries
20
+ @timeout = timeout
21
+ @logger = logger
22
+ @headers = headers
23
+ @user_agent = user_agent || construct_user_agent(send_platform_info, app_info)
72
24
  end
73
25
 
74
26
  def attributes
@@ -76,7 +28,7 @@ module DeepL
76
28
  end
77
29
 
78
30
  def ==(other)
79
- attributes == other.attributes
31
+ other.is_a?(Configuration) && attributes == other.attributes
80
32
  end
81
33
 
82
34
  # Redacts the auth key, so that it never shows in the inspect output of objects holding the
@@ -86,18 +38,15 @@ module DeepL
86
38
  "#<#{self.class.name} #{shown.map { |name, value| "#{name}=#{value.inspect}" }.join(', ')}>"
87
39
  end
88
40
 
89
- # The key is trimmed like the one sent in the Authorization header.
90
- def self.free_account_auth_key?(key)
91
- key.to_s.strip.end_with?(':fx')
92
- end
41
+ private
93
42
 
94
- def construct_user_agent(send_platform_info, app_info_name, app_info_version)
43
+ def construct_user_agent(send_platform_info, app_info)
95
44
  library_info_str = "deepl-ruby/#{DeepL::VERSION}"
96
45
  if send_platform_info
97
46
  library_info_str += " (#{RbConfig::CONFIG['host_os']}) ruby/#{RUBY_VERSION}"
98
47
  end
99
- if app_info_name && app_info_version
100
- library_info_str += " #{app_info_name}/#{app_info_version}"
48
+ if app_info&.app_name && app_info.app_version
49
+ library_info_str += " #{app_info.app_name}/#{app_info.app_version}"
101
50
  end
102
51
  library_info_str
103
52
  end
@@ -7,7 +7,7 @@ module DeepL
7
7
  module Exceptions
8
8
  class AuthorizationFailed < RequestError
9
9
  def to_s
10
- 'Authorization failed. Please supply a valid auth_key parameter.'
10
+ with_body_message('Authorization failed. Please supply a valid auth_key parameter.')
11
11
  end
12
12
  end
13
13
  end
@@ -6,15 +6,18 @@
6
6
  module DeepL
7
7
  module Exceptions
8
8
  ##
9
- # Raised by DeepL::Client and DeepL::AdminClient for a network failure without a complete
10
- # HTTP response from the API (DNS, connection, TLS, proxy, timeout or a body cut off
11
- # mid-read), after the retries are used up. Transient failures (DNS, connection, timeout,
12
- # cut-off body) are retried and have +should_retry?+ true; TLS failures, proxy failures and
13
- # malformed responses are raised at once and have +should_retry?+ false. The original
14
- # exception is available as +cause+. The module-level API raises the original exception.
9
+ # Raised by DeepL::Client and DeepL::AdminClient for a network failure without a complete HTTP
10
+ # response from the API (DNS, connection, TLS, proxy, timeout or a body cut off mid-read), after
11
+ # the retries are used up. Transient failures (DNS, connection, timeout, cut-off body) are
12
+ # retried and have +should_retry?+ true; TLS failures, proxy failures and malformed responses
13
+ # are raised at once and have +should_retry?+ false. Requests that create a resource retry only
14
+ # transient failures while connecting (DNS, refused connection, unreachable host or network,
15
+ # connection timeout, a reset during the TLS or proxy handshake), before the request is sent; of
16
+ # their other failures, only a cut-off body has +should_retry?+ true. The original exception is
17
+ # available as +cause+.
15
18
  class ConnectionError < Error
16
19
  # Raised from a +rescue+ block, so the original exception becomes +cause+.
17
- # +should_retry: false+ marks a request that is unsafe to repeat once sent.
20
+ # +should_retry: false+ marks a failure after which the request may have been processed.
18
21
  def self.from_network_error(error, should_retry: true)
19
22
  new("Connection to the DeepL API failed: #{error.message}",
20
23
  should_retry: should_retry && transient?(error))
@@ -7,7 +7,7 @@ module DeepL
7
7
  module Exceptions
8
8
  class LimitExceeded < RequestError
9
9
  def to_s
10
- 'Limit exceeded. Please wait and send your request once again.'
10
+ with_body_message('Limit exceeded. Please wait and send your request once again.')
11
11
  end
12
12
 
13
13
  def should_retry?
@@ -7,7 +7,7 @@ module DeepL
7
7
  module Exceptions
8
8
  class QuotaExceeded < RequestError
9
9
  def to_s
10
- 'Quota exceeded. The character limit has been reached.'
10
+ with_body_message('Quota exceeded. The character limit has been reached.')
11
11
  end
12
12
  end
13
13
  end
@@ -7,8 +7,7 @@ module DeepL
7
7
  module Exceptions
8
8
  class RequestEntityTooLarge < RequestError
9
9
  def to_s
10
- 'The request size has reached the supported limit. ' \
11
- "Make sure that you're not sending more than 50 text parts."
10
+ with_body_message('The request size has reached the supported limit.')
12
11
  end
13
12
  end
14
13
  end
@@ -23,6 +23,13 @@ module DeepL
23
23
 
24
24
  private
25
25
 
26
+ # +text+ followed by the API's message, if the body has one; +text+'s final period is
27
+ # dropped before it.
28
+ def with_body_message(text)
29
+ message = body_message
30
+ message ? "#{text.chomp('.')}: #{message}" : text
31
+ end
32
+
26
33
  # The +message+ of a JSON object body, else the raw body; +nil+ for an empty body.
27
34
  def body_message
28
35
  body = response&.body
@@ -13,7 +13,8 @@ module DeepL
13
13
  end
14
14
 
15
15
  def to_s
16
- 'An internal server error occured. Try again after waiting a short period.'
16
+ with_body_message('An internal server error occured. ' \
17
+ 'Try again after waiting a short period.')
17
18
  end
18
19
 
19
20
  def should_retry?
@@ -0,0 +1,32 @@
1
+ # Copyright 2026 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ module Exceptions
8
+ ##
9
+ # Any failure of DeepL::Client#import_translation_memory_from_filepath or
10
+ # #export_translation_memory_to_filepath except a missing input file. The failure being
11
+ # wrapped is the +cause+.
12
+ class TranslationMemoryJobError < Error
13
+ # @return [String, nil] ID of the import or export job, set as soon as the job was created,
14
+ # +nil+ if the failure happened before. Use it to query or resume the job.
15
+ attr_reader :job_id
16
+
17
+ # @return [DeepL::Resources::TranslationMemoryJob, nil] The last job status the helper
18
+ # fetched, +nil+ before the first status check.
19
+ attr_reader :job
20
+
21
+ # +error+ is the failure being wrapped; the HTTP status and retryability of a DeepL error
22
+ # are copied from it.
23
+ def initialize(message, job_id, job, error = nil)
24
+ deepl_error = error.is_a?(Error) ? error : nil
25
+ super(message, http_status_code: deepl_error&.http_status_code,
26
+ should_retry: deepl_error&.should_retry? || false)
27
+ @job_id = job_id
28
+ @job = job
29
+ end
30
+ end
31
+ end
32
+ end
@@ -7,8 +7,9 @@ module DeepL
7
7
  module Exceptions
8
8
  ##
9
9
  # An invalid argument detected before any request is sent: an invalid glossary or spoken
10
- # terms term, a malformed glossary TSV line, or an unsupported +DeepL.languages+ type.
11
- class ValidationError < Error
10
+ # terms term, or a malformed glossary TSV line. An ArgumentError, not a
11
+ # DeepL::Exceptions::Error, like every other invalid argument.
12
+ class ValidationError < ArgumentError
12
13
  end
13
14
  end
14
15
  end
@@ -27,6 +27,14 @@ module DeepL
27
27
  # Headers that describe the request the SDK builds; a caller's value is dropped.
28
28
  TECHNICAL_HEADERS = %w[content-type content-length transfer-encoding host].freeze
29
29
 
30
+ # A POST without a body. REQUEST_HAS_BODY false keeps Net::HTTP from sending '' with a
31
+ # default form Content-Type (net-http before 0.7).
32
+ class BodilessPost < Net::HTTPRequest
33
+ METHOD = 'POST'
34
+ REQUEST_HAS_BODY = false
35
+ RESPONSE_HAS_BODY = true
36
+ end
37
+
30
38
  # Wraps +request+ of every request class, so that a malformed response raises a
31
39
  # DeepL::Exceptions::Error instead of a raw JSON or type error.
32
40
  module ResponseFormatGuard
@@ -44,11 +52,34 @@ module DeepL
44
52
  subclass.prepend(ResponseFormatGuard)
45
53
  end
46
54
 
55
+ # Declares the options a request class accepts besides +extra_body_parameters+. Any other
56
+ # option raises ArgumentError before a request is sent.
57
+ def self.accepts_options(*names)
58
+ @accepted_options = names.map(&:to_s).freeze
59
+ end
60
+
61
+ def self.accepted_options
62
+ @accepted_options || []
63
+ end
64
+
65
+ # @raise [ArgumentError] If +options+ has an option the class does not accept.
66
+ def self.validate_options!(options)
67
+ accepted = accepted_options + ['extra_body_parameters']
68
+ unknown = options.keys.reject { |name| accepted.include?(name.to_s) }
69
+ return if unknown.empty?
70
+
71
+ names = unknown.map { |name| "`#{name}`" }.join(', ')
72
+ raise ArgumentError, "Unknown option#{'s' if unknown.size > 1} #{names}; use " \
73
+ '`extra_body_parameters` to send fields the SDK does not model'
74
+ end
75
+
47
76
  attr_reader :api, :response, :options
48
77
 
78
+ # Options set to nil are unset and not sent.
49
79
  def initialize(api, options = {}, additional_headers = {})
50
80
  @api = api
51
- @options = options
81
+ self.class.validate_options!(options)
82
+ @options = options.compact
52
83
  @additional_headers = additional_headers
53
84
  @num_retries = 0
54
85
  @backoff_timer = Utils::BackoffTimer.new
@@ -108,7 +139,7 @@ module DeepL
108
139
  end
109
140
 
110
141
  # Apply extra body parameters to multipart form data array
111
- # Extra parameters will override existing keys
142
+ # Extra parameters will override existing keys; a nil value removes the key.
112
143
  def apply_extra_body_parameters_to_form(form_data)
113
144
  return unless option?(:extra_body_parameters)
114
145
 
@@ -118,7 +149,7 @@ module DeepL
118
149
  # Remove existing key if present to allow override.
119
150
  # Required for form data as it would be duplicated otherwise
120
151
  form_data.reject! { |field| field[0].to_s == key_str }
121
- form_data.push([key_str, value.to_s])
152
+ form_data.push([key_str, value.to_s]) unless value.nil?
122
153
  end
123
154
  end
124
155
 
@@ -128,9 +159,18 @@ module DeepL
128
159
  api.configuration.logger&.debug("Request details: #{details}")
129
160
  loop do
130
161
  resp = nil
162
+ response_started = false
131
163
  client = http_client
132
164
  apply_request_timeout(client)
133
- resp = client.request(req) { |response| read_complete_body(response) }
165
+ connected = client.started?
166
+ exchange = lambda do |http|
167
+ connected = true
168
+ http.request(req) do |response|
169
+ response_started = true
170
+ read_complete_body(response)
171
+ end
172
+ end
173
+ resp = connected ? exchange.call(client) : client.start(&exchange)
134
174
  validate_response!(resp, req)
135
175
  @response_received = true
136
176
  return [req, resp]
@@ -140,22 +180,21 @@ module DeepL
140
180
  wait_before_retry(e, files_to_reset)
141
181
  next
142
182
  rescue *NETWORK_ERRORS => e
143
- raise_network_error(e) unless retry_network_error?(e)
183
+ retry_error = retry_network_error?(e, connected)
184
+ raise_network_error(e, response_started, connected) unless retry_error
144
185
 
145
186
  wait_before_retry(e, files_to_reset)
146
187
  next
147
188
  end
148
189
  end
149
190
 
150
- # Until the next major version, the module-level API raises the original network error.
151
- def raise_network_error(error)
152
- if api.client?
153
- raise Exceptions::ConnectionError.from_network_error(
154
- error, should_retry: !retry_only_unprocessed? || unprocessed_error?(error)
155
- )
156
- end
157
-
158
- raise error
191
+ # A create is not retried once the request was written. Its error has +should_retry?+
192
+ # true only for a body cut off after the response headers arrived (any transient
193
+ # failure then, the test is the phase) and false for a failure before the response.
194
+ def raise_network_error(error, response_started, connected)
195
+ should_retry = !retry_only_unprocessed? || !connected ||
196
+ (response_started && RETRYABLE_NETWORK_ERRORS.any? { error.is_a?(_1) })
197
+ raise Exceptions::ConnectionError.from_network_error(error, should_retry: should_retry)
159
198
  end
160
199
 
161
200
  # Before net-http 0.3, Net::HTTP cannot raise at EOF of a short body (+ignore_eof+), so the
@@ -198,10 +237,10 @@ module DeepL
198
237
  @backoff_timer.sleep_until_deadline
199
238
  end
200
239
 
201
- def retry_network_error?(error)
240
+ def retry_network_error?(error, connected)
202
241
  Exceptions::ConnectionError.transient?(error) &&
203
242
  @backoff_timer.num_retries < api.configuration.max_network_retries &&
204
- (!retry_only_unprocessed? || unprocessed_error?(error))
243
+ (!retry_only_unprocessed? || !connected)
205
244
  end
206
245
 
207
246
  def should_retry?(response, exception, num_retries)
@@ -214,19 +253,15 @@ module DeepL
214
253
  end
215
254
 
216
255
  # Requests that are unsafe to repeat return true to retry only failures that show the
217
- # request was not processed: HTTP 429, DNS resolution errors (SocketError), refused
218
- # connections and connection timeouts (Net::OpenTimeout).
256
+ # request was not processed: HTTP 429, and every transient network failure raised before
257
+ # the connection is up (TCP connect, proxy CONNECT, TLS handshake), when no request byte was
258
+ # written.
219
259
  def retry_only_unprocessed?
220
260
  false
221
261
  end
222
262
 
223
- def unprocessed_error?(error)
224
- error.is_a?(SocketError) || error.is_a?(Net::OpenTimeout) ||
225
- error.is_a?(Errno::ECONNREFUSED)
226
- end
227
-
228
- # The request body: the SDK's payload, then the options, then +extra_body_parameters+,
229
- # which replace an SDK field of the same name.
263
+ # The request body: the SDK's payload, then the remaining declared options, then
264
+ # +extra_body_parameters+, which replace an SDK field of the same name.
230
265
  def json_body(payload)
231
266
  body = payload.merge(options_without_extra_params).transform_keys(&:to_s)
232
267
  apply_extra_body_parameters_to_json(body)
@@ -252,6 +287,10 @@ module DeepL
252
287
  Net::HTTP::Get.new(uri.path, headers)
253
288
  end
254
289
 
290
+ def bodiless_post_request
291
+ BodilessPost.new(uri.path, headers.merge('Content-Length' => '0'))
292
+ end
293
+
255
294
  def patch_request(payload)
256
295
  http_headers = add_json_content_type(headers)
257
296
  req = Net::HTTP::Patch.new(uri.path, http_headers)
@@ -285,7 +324,7 @@ module DeepL
285
324
  # The +glossary_ids+ option accepts an array of up to `MAX_GLOSSARY_IDS` glossary
286
325
  # identifiers. Each entry may be a glossary ID string, a
287
326
  # `DeepL::Resources::Glossary` or a `DeepL::Resources::MultilingualGlossary` object. It:
288
- # * cannot be combined with the singular +glossary+ or +glossary_id+ option,
327
+ # * cannot be combined with the singular +glossary+ option,
289
328
  # * allows at most `MAX_GLOSSARY_IDS` identifiers.
290
329
  #
291
330
  # The API expects +glossary_ids+ as an array (a JSON array in the JSON translate body).
@@ -302,41 +341,41 @@ module DeepL
302
341
  return nil if ids.empty?
303
342
 
304
343
  validate_glossary_ids!(ids)
305
- ids.map { |glossary| glossary_id_string(glossary) }
344
+ ids.map { |glossary| glossary_id_string('An entry of `glossary_ids`', glossary) }
306
345
  end
307
346
 
308
347
  # Resolves the +glossary+ option (a glossary ID string, a `DeepL::Resources::Glossary` or
309
- # a `DeepL::Resources::MultilingualGlossary`) to the ID sent as +glossary_id+, and warns
310
- # about the deprecated +glossary_id+ option.
348
+ # a `DeepL::Resources::MultilingualGlossary`) to the ID sent as +glossary_id+.
311
349
  #
312
350
  # @return [String, nil] The glossary ID, or nil if the +glossary+ option is unset.
313
- # @raise [ArgumentError] If +glossary+ is combined with +glossary_id+.
314
351
  def build_glossary_param
315
- warn_glossary_id_deprecated unless option(:glossary_id).nil?
316
352
  return nil unless option?(:glossary)
317
353
 
318
354
  glossary = delete_option(:glossary)
319
355
  return nil if glossary.nil?
320
356
 
321
- unless option(:glossary_id).nil?
322
- raise ArgumentError,
323
- 'The `glossary` option cannot be used together with the `glossary_id` option'
324
- end
325
- glossary_id_string(glossary)
357
+ glossary_id_string('`glossary`', glossary)
326
358
  end
327
359
 
328
- def warn_glossary_id_deprecated
329
- Deprecation.warn_once_at_caller(
330
- 'option glossary_id',
331
- '[DEPRECATION] The glossary_id option is deprecated, use the glossary option instead.'
332
- )
360
+ def glossary_id_string(name, glossary)
361
+ resource_id!(name, glossary,
362
+ [DeepL::Resources::Glossary, DeepL::Resources::MultilingualGlossary], :id)
333
363
  end
334
364
 
335
- def glossary_id_string(glossary)
336
- return glossary.id if glossary.is_a?(DeepL::Resources::Glossary)
337
- return glossary.id if glossary.is_a?(DeepL::Resources::MultilingualGlossary)
365
+ # Removes the resource option +name+ and returns its ID, nil if the option is unset or nil.
366
+ def take_resource_option(name, types, id_method)
367
+ value = delete_option(name)
368
+ resource_id!("`#{name}`", value, types, id_method) unless value.nil?
369
+ end
338
370
 
339
- glossary.to_s
371
+ # Resolves +value+, an ID or a resource object of one of +types+, to the ID.
372
+ #
373
+ # @raise [ArgumentError] If the ID is nil or empty.
374
+ def resource_id!(name, value, types, id_method)
375
+ id = types.any? { |type| value.is_a?(type) } ? value.public_send(id_method) : value
376
+ return id.to_s unless id.to_s.empty?
377
+
378
+ raise ArgumentError, "#{name} must be a non-empty ID or a resource object with its ID"
340
379
  end
341
380
 
342
381
  def validate_glossary_ids!(ids)
@@ -348,13 +387,52 @@ module DeepL
348
387
  end
349
388
 
350
389
  def validate_no_single_glossary!
351
- single = if !option(:glossary).nil? then 'glossary'
352
- elsif !option(:glossary_id).nil? then 'glossary_id'
353
- end
354
- return unless single
390
+ return if option(:glossary).nil?
391
+
392
+ raise ArgumentError,
393
+ 'The `glossary_ids` option cannot be used together with the `glossary` option'
394
+ end
395
+
396
+ # @raise [ArgumentError] Unless +text+ is a non-empty string or a non-empty array of
397
+ # non-empty strings.
398
+ def validate_text!(text)
399
+ texts = text.is_a?(Array) ? text : [text]
400
+ return unless texts.empty? || texts.any? { |t| t.to_s.empty? }
401
+
402
+ raise ArgumentError,
403
+ '`text` must be a non-empty string or a non-empty array of non-empty strings'
404
+ end
405
+
406
+ # @raise [ArgumentError] If +target_lang+ is empty or +source_lang+ is given but empty.
407
+ def validate_languages!(source_lang, target_lang)
408
+ raise ArgumentError, '`target_lang` must not be empty' if target_lang.to_s.empty?
409
+ return unless !source_lang.nil? && source_lang.to_s.empty?
410
+
411
+ raise ArgumentError, '`source_lang` must not be empty; pass nil to detect it'
412
+ end
413
+
414
+ # @raise [ArgumentError] If the language is empty, or nil unless +optional+. An optional
415
+ # language that is nil is not sent.
416
+ def validate_language!(name, language, optional: false)
417
+ return unless language.to_s.empty?
418
+ return if optional && language.nil?
355
419
 
356
420
  raise ArgumentError,
357
- "The `glossary_ids` option cannot be used together with the `#{single}` option"
421
+ "`#{name}` must not be empty#{'; pass nil to leave it unset' if optional}"
422
+ end
423
+
424
+ # @raise [ArgumentError] If the +translation_memory_threshold+ option is set without the
425
+ # +translation_memory+ option or is not from 0 to 100.
426
+ def validate_translation_memory_threshold!
427
+ threshold = option(:translation_memory_threshold)
428
+ return if threshold.nil?
429
+
430
+ unless option?(:translation_memory)
431
+ raise ArgumentError, '`translation_memory_threshold` requires `translation_memory`'
432
+ end
433
+ return if threshold.between?(0, 100)
434
+
435
+ raise ArgumentError, '`translation_memory_threshold` must be from 0 to 100'
358
436
  end
359
437
 
360
438
  def path
@@ -373,7 +451,7 @@ module DeepL
373
451
  end
374
452
 
375
453
  def url
376
- "#{host}/#{api.configuration.version}/#{path}"
454
+ "#{host}/v2/#{path}"
377
455
  end
378
456
 
379
457
  def uri
@@ -14,7 +14,8 @@ module DeepL
14
14
  super(api, options, additional_headers)
15
15
  @text = text
16
16
  @target_lang = target_lang
17
- validate_text!
17
+ validate_text!(text)
18
+ validate_optional_target_lang!(target_lang)
18
19
  end
19
20
 
20
21
  def request
@@ -37,13 +38,6 @@ module DeepL
37
38
  text.is_a?(Array) ? text : [text]
38
39
  end
39
40
 
40
- def validate_text!
41
- return unless text_arrayified.empty? || text_arrayified.any? { |t| t.to_s.empty? }
42
-
43
- raise ArgumentError,
44
- '`text` must be a non-empty string or a non-empty array of non-empty strings'
45
- end
46
-
47
41
  def build_texts(request, response)
48
42
  texts = build_improvements(text_arrayified.size, request, response)
49
43
  text.is_a?(Array) ? texts : texts.first