blog_verification 1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f4e30db2372c43909004ba3957b8b16395fe38612a58d42729d8436b4a352295
4
+ data.tar.gz: de9120839b129627959fd1ee8009edf77a18946619819b8b0079b65c1808de61
5
+ SHA512:
6
+ metadata.gz: 1e0e7a2a96f8e3cf95d3b299d6081c9105d82389541a2588d38940070eaf03bbbcb683303f8f47c9e2bdfa9e529a80946ccf5b8794e0b46246c1cc0ec05b46e5
7
+ data.tar.gz: 251e21438613a10575b486fe5d9c28912d8af49c9d9fe92382d6917b66deca802faa1dac5f0274efb8b8eab9913956ca7dd382231d5563cc8b76835882e17011
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blog Verification Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,413 @@
1
+ # BlogVerification — Ruby Gem
2
+
3
+ A robust, lightweight Ruby Gem for verifying whether a submitted blog URL belongs to the expected author, was published in the current quarter, contains sufficient article length, and matches expected topic, summary, and tag metadata.
4
+
5
+ Built for **Ruby on Rails** applications and standalone Ruby backends.
6
+
7
+ Supports **Medium** and **DEV Community (`dev.to`)**.
8
+
9
+ ---
10
+
11
+ ## Key Features
12
+
13
+ - **Strict Ruby 2.7.8+ Compatibility**: Compatible with Ruby 2.7.8 through modern Ruby 3.x, tested across standard MRI runtimes.
14
+ - **Identical Input & Output Contract**: Produces the exact same structured JSON/Hash responses, error codes, and field checks as the original Node.js REST API.
15
+ - **Rails Integration**:
16
+ - Direct helper: `BlogVerification.verify(params)`
17
+ - ActiveModel / ActiveRecord validation: `validates :url, blog_verification: { ... }`
18
+ - **Platform Adapters**:
19
+ - **DEV Community**: Official Forem API integration with canonical author extraction, tag lists, publication timestamps, and excerpts.
20
+ - **Medium**: Parses JSON-LD structured data (`NewsArticle`/`BlogPosting`) to extract canonical author identifiers (`author.identifier`, `@id`, `url`), publication timestamps, tags, and body content.
21
+ - **Current Quarter Verification**:
22
+ - Automatically verifies whether the blog was created in the current quarter:
23
+ - **Quarter 1**: April 1 – June 30
24
+ - **Quarter 2**: July 1 – September 30
25
+ - **Quarter 3**: October 1 – December 31
26
+ - **Quarter 4**: January 1 – March 31
27
+ - Out-of-quarter articles fail with `NOT_IN_CURRENT_QUARTER`.
28
+ - Supports optional `reference_date` (`YYYY-MM-DD`) for deterministic testing.
29
+ - **Article Word Count (Length Check)**:
30
+ - Strips HTML tags and markdown formatting to count body words.
31
+ - Verifies minimum word count (default: 500 words). Articles under 500 words fail with `INSUFFICIENT_CONTENT_LENGTH`.
32
+ - **SSRF & Outbound Security**:
33
+ - Validates URL syntax, protocols (HTTPS), and approved hosts.
34
+ - Verifies destination IP addresses against private and loopback CIDR blocks before connecting.
35
+ - Safely follows HTTP redirects up to a maximum depth of 5, re-validating destination hosts and IPs at every hop.
36
+
37
+ ---
38
+
39
+ ## Installation
40
+
41
+ ### In a Ruby on Rails Application
42
+
43
+ Add this line to your application's `Gemfile`:
44
+
45
+ ```ruby
46
+ gem 'blog_verification'
47
+ ```
48
+
49
+ And then execute:
50
+
51
+ ```bash
52
+ bundle install
53
+ ```
54
+
55
+ ### In Plain Ruby or CLI
56
+
57
+ Install directly via RubyGems:
58
+
59
+ ```bash
60
+ gem install blog_verification
61
+ ```
62
+
63
+ ---
64
+
65
+ ## Usage in Ruby on Rails
66
+
67
+ ### 1. In Controllers or Service Objects
68
+
69
+ You can call `BlogVerification.verify` using either **symbols** or **strings** for keys:
70
+
71
+ ```ruby
72
+ class BlogSubmissionsController < ApplicationController
73
+ def verify
74
+ result = BlogVerification.verify(
75
+ platform: params[:platform], # 'medium' or 'devto'
76
+ url: params[:url], # Full article URL
77
+ username: params[:username], # Expected author username
78
+ published_at: params[:published_at], # 'YYYY-MM-DD'
79
+ tags: params[:tags], # Optional array of strings
80
+ topic: params[:topic], # 'Backend Development'
81
+ summary: params[:summary], # Expected description
82
+ min_word_count: 500 # Optional, defaults to 500
83
+ )
84
+
85
+ case result['status']
86
+ when 'valid'
87
+ render json: { success: true, message: 'Blog verified successfully!', data: result['data'] }
88
+ when 'invalid'
89
+ render json: { success: false, errors: result['errors'], data: result['data'] }, status: :unprocessable_entity
90
+ when 'unverified'
91
+ render json: { success: false, message: 'Upstream platform unavailable.', errors: result['errors'] }, status: :service_unavailable
92
+ else
93
+ render json: { success: false, errors: result['errors'] }, status: :bad_request
94
+ end
95
+ end
96
+ end
97
+ ```
98
+
99
+ ### 2. In ActiveRecord Models (Custom Validator)
100
+
101
+ The gem comes with an ActiveModel validator out-of-the-box:
102
+
103
+ ```ruby
104
+ class ArticleSubmission < ApplicationRecord
105
+ # Attributes: platform, url, author_username, publication_date, topic, summary, tags
106
+
107
+ validates :url, presence: true, blog_verification: {
108
+ platform: :platform,
109
+ username: :author_username,
110
+ published_at: :publication_date,
111
+ topic: :topic,
112
+ summary: :summary,
113
+ tags: :tags,
114
+ min_word_count: 500
115
+ }
116
+ end
117
+ ```
118
+
119
+ When calling `article_submission.valid?`, the validator automatically performs the verification. Any verification errors (e.g. `AUTHOR_MISMATCH`, `NOT_IN_CURRENT_QUARTER`, `INSUFFICIENT_CONTENT_LENGTH`) are appended to `article_submission.errors[:url]`.
120
+
121
+ ---
122
+
123
+ ## Configuration
124
+
125
+ You can configure global gem settings via an initializer (e.g. `config/initializers/blog_verification.rb` in Rails):
126
+
127
+ ```ruby
128
+ BlogVerification.configure do |config|
129
+ config.request_timeout = 5.0 # Outbound request timeout in seconds (default: 5.0)
130
+ config.max_redirects = 5 # Maximum redirects to follow (default: 5)
131
+ config.require_https = true # Require HTTPS URLs in production (default: true)
132
+ config.skip_dns_check = false # Set true only in offline/mock testing environments
133
+ end
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Input & Output Specification
139
+
140
+ ### Input Hash
141
+
142
+ Both `camelCase` and `snake_case` keys are supported:
143
+
144
+ | Field | Type | Required | Description |
145
+ |---|---|---|---|
146
+ | `platform` | String | **Yes** | `"devto"` or `"medium"` |
147
+ | `url` | String | **Yes** | Article HTTPS URL |
148
+ | `username` | String | **Yes** | Expected canonical author username |
149
+ | `published_at` / `publishedAt` | String | **Yes** | Original publication date in `YYYY-MM-DD` |
150
+ | `tags` | Array of strings | No | Expected tags; omitting or `[]` skips validation |
151
+ | `topic` | String | **Yes** | Expected topic matching taxonomy |
152
+ | `summary` | String | **Yes** | Expected official description or excerpt |
153
+ | `min_word_count` / `minWordCount` | Integer | No | Minimum required word count (default: `500`) |
154
+ | `reference_date` / `referenceDate` | String | No | Custom reference date (`YYYY-MM-DD`) for quarterly verification (default: today) |
155
+
156
+ ---
157
+
158
+ ### Output Hash Examples
159
+
160
+ #### 1. Valid Blog Verification
161
+
162
+ ```json
163
+ {
164
+ "success": true,
165
+ "status": "valid",
166
+ "message": "Blog verification completed successfully.",
167
+ "data": {
168
+ "platform": "medium",
169
+ "url": "https://medium.com/@thedevankit/mastering-clean-architecture-in-nodejs-abc12345",
170
+ "checks": {
171
+ "url": { "status": "passed" },
172
+ "username": {
173
+ "status": "passed",
174
+ "expected": "thedevankit",
175
+ "actual": "thedevankit"
176
+ },
177
+ "publishedAt": {
178
+ "status": "passed",
179
+ "expected": "2026-10-15",
180
+ "actual": "2026-10-15"
181
+ },
182
+ "quarter": {
183
+ "status": "passed",
184
+ "currentQuarter": "October - December 2026",
185
+ "blogQuarter": "October - December 2026",
186
+ "message": "Blog publication date is in the current quarter (October - December 2026)."
187
+ },
188
+ "tags": {
189
+ "status": "passed",
190
+ "expected": ["architecture", "express", "nodejs"],
191
+ "actual": ["architecture", "express", "nodejs"]
192
+ },
193
+ "topic": {
194
+ "status": "passed",
195
+ "expected": "Backend Development",
196
+ "actual": "Backend Development"
197
+ },
198
+ "summary": { "status": "passed" },
199
+ "contentLength": {
200
+ "status": "passed",
201
+ "wordCount": 850,
202
+ "minRequired": 500,
203
+ "message": "Blog length passed (850 words >= 500 words)."
204
+ }
205
+ }
206
+ }
207
+ }
208
+ ```
209
+
210
+ #### 2. Failed Verification (Mismatch / Out of Quarter / Short Length)
211
+
212
+ ```json
213
+ {
214
+ "success": true,
215
+ "status": "invalid",
216
+ "message": "Blog verification failed.",
217
+ "errors": [
218
+ {
219
+ "code": "NOT_IN_CURRENT_QUARTER",
220
+ "field": "publishedAt",
221
+ "message": "Blog publication date is not in the current quarter. Expected October - December 2026, but blog was published in April - June 2026.",
222
+ "expected": "October - December 2026",
223
+ "actual": "April - June 2026"
224
+ },
225
+ {
226
+ "code": "INSUFFICIENT_CONTENT_LENGTH",
227
+ "field": "contentLength",
228
+ "message": "The blog content does not meet the minimum required length of 500 words.",
229
+ "expected": 500,
230
+ "actual": 250
231
+ }
232
+ ],
233
+ "data": {
234
+ "platform": "medium",
235
+ "url": "https://medium.com/@thedevankit/mastering-clean-architecture-in-nodejs-abc12345",
236
+ "checks": {
237
+ "url": { "status": "passed" },
238
+ "username": { "status": "passed" },
239
+ "publishedAt": { "status": "passed" },
240
+ "quarter": { "status": "failed" },
241
+ "tags": { "status": "passed" },
242
+ "topic": { "status": "passed" },
243
+ "summary": { "status": "passed" },
244
+ "contentLength": { "status": "failed", "wordCount": 250, "minRequired": 500 }
245
+ }
246
+ }
247
+ }
248
+ ```
249
+
250
+ ---
251
+
252
+ ## Error Codes
253
+
254
+ | Error Code | Meaning |
255
+ |---|---|
256
+ | `INVALID_REQUEST` | Input payload or date format is malformed |
257
+ | `MISSING_REQUIRED_FIELD` | A required field (`platform`, `url`, `username`, `publishedAt`, `topic`, `summary`) is missing |
258
+ | `INVALID_PLATFORM` | Platform is not `'medium'` or `'devto'` |
259
+ | `INVALID_URL` | URL is malformed, uses an unsupported host, or targets an index/profile page |
260
+ | `UNSAFE_URL` | URL or redirect targets loopback or private network (SSRF protection) |
261
+ | `ARTICLE_NOT_FOUND` | Source platform confirms article does not exist |
262
+ | `ARTICLE_ACCESS_DENIED` | Article is restricted, paywalled, or private |
263
+ | `AUTHOR_MISMATCH` | Expected username does not match canonical platform username |
264
+ | `PUBLICATION_DATE_MISMATCH` | Expected date does not match source publication date (UTC) |
265
+ | `NOT_IN_CURRENT_QUARTER` | Blog publication date is outside the current quarter |
266
+ | `INSUFFICIENT_CONTENT_LENGTH` | Article word count is under the required minimum (default 500) |
267
+ | `TAGS_MISMATCH` | Supplied tags do not match article tags |
268
+ | `TOPIC_MISMATCH` | Expected topic does not match verified topic |
269
+ | `SUMMARY_MISMATCH` | Expected summary does not match description |
270
+ | `SOURCE_RATE_LIMITED` | Source platform rate limited the request |
271
+ | `SOURCE_TIMEOUT` | Upstream platform timed out |
272
+ | `SOURCE_UNAVAILABLE` | Upstream platform is down |
273
+
274
+ ---
275
+
276
+ # Step-by-Step Guide to Uploading the Gem to RubyGems.org
277
+
278
+ Follow these instructions to build, package, and publish `blog_verification` to the official RubyGems library ([rubygems.org](https://rubygems.org)).
279
+
280
+ ### Step 1: Create a RubyGems.org Account
281
+
282
+ 1. Go to [https://rubygems.org/sign_up](https://rubygems.org/sign_up) and register an account.
283
+ 2. Verify your email address.
284
+ 3. Enable Multi-Factor Authentication (MFA) in your account settings (RubyGems now requires MFA for gem maintainers).
285
+
286
+ ---
287
+
288
+ ### Step 2: Configure RubyGems API Credentials on Your Machine
289
+
290
+ Open your terminal and run:
291
+
292
+ ```bash
293
+ gem signin
294
+ ```
295
+
296
+ Enter your RubyGems email and password. When prompted, enter your MFA code. This will save your API key securely into `~/.gem/credentials`.
297
+
298
+ Alternatively, you can manually set your API key:
299
+
300
+ ```bash
301
+ curl -u <your-username> https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials
302
+ chmod 0600 ~/.gem/credentials
303
+ ```
304
+
305
+ ---
306
+
307
+ ### Step 3: Verify Gem Metadata
308
+
309
+ Open `blog_verification.gemspec` and ensure the following fields are personalized:
310
+
311
+ - `spec.name`: Must be unique on RubyGems.org. If `blog_verification` is already taken, you can name it `blog_verification_api` or `my_org_blog_verification`.
312
+ - `spec.version`: Ensure `lib/blog_verification/version.rb` is set (e.g. `'1.0.0'`).
313
+ - `spec.authors`: Your name or organization.
314
+ - `spec.email`: Your contact email.
315
+ - `spec.homepage`: Your repository URL (e.g. GitHub URL).
316
+
317
+ ---
318
+
319
+ ### Step 4: Run the Test Suite
320
+
321
+ Before releasing, execute the test suite to ensure all tests pass:
322
+
323
+ ```bash
324
+ bundle install
325
+ bundle exec rspec
326
+ ```
327
+
328
+ All unit and integration specs should pass.
329
+
330
+ ---
331
+
332
+ ### Step 5: Build the Gem Package
333
+
334
+ In the `rubyGeM` root directory, run:
335
+
336
+ ```bash
337
+ gem build blog_verification.gemspec
338
+ ```
339
+
340
+ Output:
341
+ ```text
342
+ Successfully built RubyGem
343
+ Name: blog_verification
344
+ Version: 1.0.0
345
+ File: blog_verification-1.0.0.gem
346
+ ```
347
+
348
+ This creates the packaged binary file: `blog_verification-1.0.0.gem`.
349
+
350
+ ---
351
+
352
+ ### Step 6: Test the Gem Locally (Optional but Recommended)
353
+
354
+ You can install the newly built gem locally to verify that it installs and loads cleanly:
355
+
356
+ ```bash
357
+ gem install ./blog_verification-1.0.0.gem
358
+ ```
359
+
360
+ Test it in `irb`:
361
+
362
+ ```ruby
363
+ require 'blog_verification'
364
+
365
+ BlogVerification::VERSION
366
+ # => "1.0.0"
367
+ ```
368
+
369
+ ---
370
+
371
+ ### Step 7: Push the Gem to RubyGems.org
372
+
373
+ Publish your gem to the global Ruby community with:
374
+
375
+ ```bash
376
+ gem push blog_verification-1.0.0.gem
377
+ ```
378
+
379
+ If your account has MFA enabled, you will be prompted for your OTP code:
380
+
381
+ ```text
382
+ Pushing gem to https://rubygems.org...
383
+ Enter your MFA code: 123456
384
+ Successfully registered gem: blog_verification (1.0.0)
385
+ ```
386
+
387
+ ---
388
+
389
+ ### Step 8: Verify Your Published Gem
390
+
391
+ Your gem will be immediately live and indexable! Visit:
392
+
393
+ ```
394
+ https://rubygems.org/gems/blog_verification
395
+ ```
396
+
397
+ Now any developer in the world can install your gem with:
398
+
399
+ ```bash
400
+ gem install blog_verification
401
+ ```
402
+
403
+ Or add it to their Rails `Gemfile`:
404
+
405
+ ```ruby
406
+ gem 'blog_verification', '~> 1.0'
407
+ ```
408
+
409
+ ---
410
+
411
+ ## License
412
+
413
+ The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/blog_verification/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'blog_verification'
7
+ spec.version = BlogVerification::VERSION
8
+ spec.authors = ['Ankitkumar Singh (thedevankit)']
9
+ spec.email = ['thedevankit@gmail.com']
10
+
11
+ spec.summary = 'Lightweight blog verification library for Medium and DEV Community'
12
+ spec.description = 'Verifies whether a submitted blog URL belongs to the claimed author, matches publication date and quarter, meets minimum word length, and matches expected topic and summary metadata.'
13
+ spec.homepage = 'https://github.com/thedevankit/blog_verification'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 2.7.8'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/main/CHANGELOG.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ Dir.glob('lib/**/*', File::FNM_DOTMATCH).reject { |f| File.directory?(f) } +
24
+ %w[LICENSE.txt README.md blog_verification.gemspec]
25
+ end
26
+
27
+ spec.bindir = 'exe'
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ['lib']
30
+
31
+ # Runtime dependencies
32
+ # nokogiri is used for robust HTML / JSON-LD parsing; supported on Ruby >= 2.7.8
33
+ spec.add_dependency 'nokogiri', '>= 1.13.0', '< 2.0'
34
+
35
+ # Development dependencies
36
+ spec.add_development_dependency 'bundler', '~> 2.1'
37
+ spec.add_development_dependency 'rake', '~> 13.0'
38
+ spec.add_development_dependency 'rspec', '~> 3.12'
39
+ spec.add_development_dependency 'webmock', '~> 3.18'
40
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BlogVerification
4
+ module Adapters
5
+ class BaseAdapter
6
+ attr_reader :platform
7
+
8
+ def initialize(platform)
9
+ @platform = platform.to_s
10
+ end
11
+
12
+ # Retrieves and normalizes article metadata from the source platform.
13
+ # Returns a Hash containing:
14
+ # - canonical_url
15
+ # - platform
16
+ # - author: { username: ..., display_name: ... }
17
+ # - published_at
18
+ # - updated_at
19
+ # - tags
20
+ # - topic
21
+ # - description
22
+ # - content
23
+ # - word_count
24
+ # - raw_metadata
25
+ def get_article_metadata(_url, _options = {})
26
+ raise NotImplementedError, "#{self.class}#get_article_metadata must be implemented."
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base_adapter'
4
+ require_relative '../utils/url_security'
5
+ require_relative '../utils/normalizer'
6
+ require_relative '../errors'
7
+ require_relative '../constants/error_codes'
8
+
9
+ module BlogVerification
10
+ module Adapters
11
+ class DevtoAdapter < BaseAdapter
12
+ def initialize
13
+ super('devto')
14
+ end
15
+
16
+ # Builds the official Forem / DEV.to API endpoint URL for an article URL
17
+ def build_api_url(url_string)
18
+ parsed = Utils::UrlSecurity.validate_article_url(url_string, 'devto')
19
+ path = (parsed.path || '').gsub(%r{/+\z}, '')
20
+ segments = path.split('/').reject(&:empty?)
21
+
22
+ if segments.length >= 2
23
+ return "https://dev.to/api/articles/#{segments[0]}/#{segments[1]}"
24
+ end
25
+
26
+ raise UpstreamError.new(ErrorCodes::INVALID_URL, 'Could not determine DEV.to article path.')
27
+ end
28
+
29
+ # Retrieves metadata for a DEV.to article using the official Forem API
30
+ def get_article_metadata(url, _options = {})
31
+ api_url = build_api_url(url)
32
+
33
+ response = Utils::UrlSecurity.safe_fetch(
34
+ api_url,
35
+ {
36
+ headers: {
37
+ 'Accept' => 'application/json',
38
+ 'User-Agent' => BlogVerification.configuration.user_agent
39
+ }
40
+ },
41
+ 'devto'
42
+ )
43
+
44
+ case response.status
45
+ when 404
46
+ raise UpstreamError.new(ErrorCodes::ARTICLE_NOT_FOUND, 'The specified article does not exist on DEV Community.', 404)
47
+ when 401, 403
48
+ raise UpstreamError.new(ErrorCodes::ARTICLE_ACCESS_DENIED, 'Access to the DEV Community article is restricted.', response.status)
49
+ when 429
50
+ raise UpstreamError.new(ErrorCodes::SOURCE_RATE_LIMITED, 'DEV Community API rate limit exceeded.', 429)
51
+ else
52
+ if response.status >= 500
53
+ raise UpstreamError.new(ErrorCodes::SOURCE_UNAVAILABLE, "DEV Community returned HTTP #{response.status}.", response.status)
54
+ elsif !response.ok?
55
+ raise UpstreamError.new(ErrorCodes::SOURCE_RESPONSE_INVALID, "DEV Community returned unexpected status #{response.status}.", response.status)
56
+ end
57
+ end
58
+
59
+ data = response.json
60
+ unless data.is_a?(Hash)
61
+ raise UpstreamError.new(ErrorCodes::SOURCE_RESPONSE_INVALID, 'Malformed JSON payload from DEV Community.')
62
+ end
63
+
64
+ # Extract tags
65
+ tags = if data['tag_list'].is_a?(Array)
66
+ data['tag_list']
67
+ elsif data['tags'].is_a?(Array)
68
+ data['tags']
69
+ elsif data['tags'].is_a?(String)
70
+ data['tags'].split(',').map(&:strip).reject(&:empty?)
71
+ end
72
+
73
+ # Extract body content and word count
74
+ content = data['body_markdown'] || data['body_html']
75
+ word_count = content ? Utils::Normalizer.count_words(content) : nil
76
+
77
+ user_hash = data['user'].is_a?(Hash) ? data['user'] : {}
78
+
79
+ {
80
+ canonical_url: data['canonical_url'] || data['url'] || url,
81
+ platform: 'devto',
82
+ author: {
83
+ username: user_hash['username'],
84
+ display_name: user_hash['name']
85
+ },
86
+ published_at: data['published_at'],
87
+ updated_at: data['edited_at'],
88
+ tags: tags,
89
+ topic: nil, # Resolved via taxonomy mapping
90
+ description: data['description'],
91
+ content: content,
92
+ word_count: word_count,
93
+ raw_metadata: data
94
+ }
95
+ end
96
+ end
97
+ end
98
+ end