hooktrace 0.1.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.
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooktrace
4
+ class Error
5
+ attr_reader :path, :code, :message
6
+
7
+ def initialize(path:, code:, message:)
8
+ @path = path.freeze
9
+ @code = code.freeze
10
+ @message = message.freeze
11
+ freeze
12
+ end
13
+
14
+ def to_h
15
+ {
16
+ path: path,
17
+ code: code,
18
+ message: message
19
+ }
20
+ end
21
+
22
+ def ==(other)
23
+ other.is_a?(self.class) &&
24
+ path == other.path &&
25
+ code == other.code &&
26
+ message == other.message
27
+ end
28
+ alias eql? ==
29
+
30
+ def hash
31
+ [path, code, message].hash
32
+ end
33
+
34
+ def to_s
35
+ "#{path}: [#{code}] #{message}"
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module Hooktrace
7
+ class EventRecord
8
+ attr_reader :id, :event_type, :provider, :received_at, :valid, :errors, :payload
9
+
10
+ def self.from_h(hash)
11
+ data = hash.transform_keys(&:to_s)
12
+ new(
13
+ id: data.fetch("id"),
14
+ event_type: data.fetch("event_type"),
15
+ provider: data["provider"],
16
+ received_at: data["received_at"],
17
+ valid: data.fetch("valid", false),
18
+ errors: data["errors"] || [],
19
+ payload: data["payload"] || {}
20
+ )
21
+ end
22
+
23
+ def initialize(id:, event_type:, valid:, errors: [], payload: {}, provider: nil, received_at: nil)
24
+ @id = id.to_s.freeze
25
+ @event_type = event_type.to_s.freeze
26
+ @provider = (provider || detect_provider(@event_type, payload)).to_s.freeze
27
+ @received_at = (received_at || Time.now.utc.iso8601).to_s.freeze
28
+ @valid = [true, "true"].include?(valid)
29
+ @errors = errors.freeze
30
+ @payload = payload.freeze
31
+ freeze
32
+ end
33
+
34
+ def valid?
35
+ @valid
36
+ end
37
+
38
+ def invalid?
39
+ !@valid
40
+ end
41
+
42
+ def to_h
43
+ {
44
+ id: id,
45
+ event_type: event_type,
46
+ provider: provider,
47
+ received_at: received_at,
48
+ valid: valid?,
49
+ error_count: errors.size,
50
+ errors: errors,
51
+ payload: payload
52
+ }
53
+ end
54
+
55
+ def to_json(*args)
56
+ JSON.generate(to_h, *args)
57
+ end
58
+
59
+ private
60
+
61
+ def detect_provider(type, payload)
62
+ if type.start_with?("stripe.") || payload["object"] == "event"
63
+ "stripe"
64
+ elsif type.start_with?("paypal.") || payload["resource_type"]
65
+ "paypal"
66
+ else
67
+ "unknown"
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hooktrace
4
+ class Field
5
+ TYPES = %i[
6
+ string integer number boolean object array null
7
+ ].freeze
8
+
9
+ attr_reader :name, :type, :required, :nullable, :fields, :item_type, :item_fields
10
+
11
+ def initialize(name:, type:, required: true, nullable: false, fields: [], item_type: nil, item_fields: [])
12
+ unless TYPES.include?(type)
13
+ raise ArgumentError, "Unsupported type: #{type.inspect}. Supported types are #{TYPES.map(&:inspect).join(", ")}"
14
+ end
15
+
16
+ @name = name.to_s.freeze
17
+ @type = type
18
+ @required = !required.nil? && required != false
19
+ @nullable = !nullable.nil? && nullable != false
20
+ @fields = fields.freeze
21
+ @item_type = item_type
22
+ @item_fields = item_fields.freeze
23
+ freeze
24
+ end
25
+
26
+ def required?
27
+ @required
28
+ end
29
+
30
+ def optional?
31
+ !@required
32
+ end
33
+
34
+ def nullable?
35
+ @nullable
36
+ end
37
+
38
+ def object?
39
+ @type == :object
40
+ end
41
+
42
+ def array?
43
+ @type == :array
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "set"
6
+ require "uri"
7
+
8
+ module Hooktrace
9
+ module Importers
10
+ class OpenApiSchemaConverter
11
+ def self.load_spec(source)
12
+ raw = if source.start_with?("http://", "https://")
13
+ fetch_http(source)
14
+ else
15
+ File.read(source, encoding: "UTF-8")
16
+ end
17
+ JSON.parse(raw)
18
+ end
19
+
20
+ def self.fetch_http(url, limit = 5)
21
+ raise Hooktrace::StandardError, "Too many HTTP redirects fetching #{url}" if limit.zero?
22
+
23
+ res = Net::HTTP.get_response(URI(url))
24
+ return res.body if res.is_a?(Net::HTTPSuccess)
25
+ return fetch_http(res["location"], limit - 1) if res.is_a?(Net::HTTPRedirection) && res["location"]
26
+
27
+ raise Hooktrace::StandardError, "Failed to fetch OpenAPI spec (#{res.code} #{res.message}) from #{url}"
28
+ end
29
+
30
+ def initialize(max_depth: 2)
31
+ @max_depth = max_depth
32
+ end
33
+
34
+ def build_fields(schema_or_ref, schemas, depth:, visited:, extra_required: [])
35
+ return [] if depth > @max_depth
36
+
37
+ properties, required_list, next_visited = collect_object_schema(schema_or_ref, schemas, visited)
38
+ return [] if properties.empty?
39
+
40
+ required_set = Set.new((required_list + extra_required).map(&:to_s))
41
+
42
+ properties.keys.sort.map do |prop_name|
43
+ convert_property(
44
+ prop_name,
45
+ properties[prop_name],
46
+ schemas,
47
+ required: required_set.include?(prop_name),
48
+ depth: depth,
49
+ visited: next_visited
50
+ )
51
+ end
52
+ end
53
+
54
+ private
55
+
56
+ def collect_object_schema(schema_or_ref, schemas, visited)
57
+ schema, next_visited = resolve_schema(schema_or_ref, schemas, visited)
58
+ return [{}, [], next_visited] unless schema.is_a?(Hash)
59
+
60
+ props = {}
61
+ reqs = []
62
+
63
+ Array(schema["allOf"]).each do |sub|
64
+ sub_props, sub_reqs, next_visited = collect_object_schema(sub, schemas, next_visited)
65
+ props.merge!(sub_props)
66
+ reqs.concat(sub_reqs)
67
+ end
68
+
69
+ props.merge!(schema["properties"]) if schema["properties"].is_a?(Hash)
70
+ reqs.concat(schema["required"]) if schema["required"].is_a?(Array)
71
+
72
+ [props, reqs.uniq, next_visited]
73
+ end
74
+
75
+ def convert_property(name, prop_schema, schemas, required:, depth:, visited:)
76
+ nullable = prop_schema.is_a?(Hash) && prop_schema["nullable"] == true
77
+ effective_schema, next_visited = unwrap_combinators(prop_schema, schemas, visited)
78
+ nullable ||= effective_schema["nullable"] == true
79
+
80
+ field_type = map_type(effective_schema, schemas, next_visited)
81
+ result = {
82
+ "name" => name,
83
+ "type" => field_type,
84
+ "required" => required,
85
+ "nullable" => nullable
86
+ }
87
+
88
+ if field_type == "object" && depth < @max_depth
89
+ nested = build_fields(effective_schema, schemas, depth: depth + 1, visited: next_visited)
90
+ result["fields"] = nested unless nested.empty?
91
+ elsif field_type == "array"
92
+ apply_array_metadata(result, effective_schema, schemas, depth: depth, visited: next_visited)
93
+ end
94
+
95
+ result
96
+ end
97
+
98
+ def apply_array_metadata(result, array_schema, schemas, depth:, visited:)
99
+ items = array_schema["items"]
100
+ return unless items.is_a?(Hash)
101
+
102
+ resolved_item, next_visited = unwrap_combinators(items, schemas, visited)
103
+ item_type = map_type(resolved_item, schemas, next_visited)
104
+ result["item_type"] = item_type
105
+
106
+ return unless item_type == "object" && depth < @max_depth
107
+
108
+ item_fields = build_fields(resolved_item, schemas, depth: depth + 1, visited: next_visited)
109
+ result["item_fields"] = item_fields unless item_fields.empty?
110
+ end
111
+
112
+ def resolve_schema(schema_or_ref, schemas, visited)
113
+ return [{}, visited] unless schema_or_ref.is_a?(Hash)
114
+
115
+ if schema_or_ref["$ref"]
116
+ ref_name = schema_or_ref["$ref"].split("/").last
117
+ return [{}, visited] if visited.include?(ref_name)
118
+
119
+ target = schemas[ref_name] || {}
120
+ return resolve_schema(target, schemas, visited + [ref_name])
121
+ end
122
+
123
+ [schema_or_ref, visited]
124
+ end
125
+
126
+ def unwrap_combinators(prop_schema, schemas, visited)
127
+ return resolve_schema(prop_schema, schemas, visited) unless prop_schema.is_a?(Hash)
128
+
129
+ variants = prop_schema["anyOf"] || prop_schema["oneOf"]
130
+ if variants.is_a?(Array) && !variants.empty?
131
+ primitive = variants.find { |v| v.is_a?(Hash) && v["type"] && v["type"] != "null" && !v.key?("$ref") }
132
+ return [primitive, visited] if primitive
133
+
134
+ non_null = variants.find { |v| v.is_a?(Hash) && v["type"] != "null" }
135
+ return resolve_schema(non_null, schemas, visited) if non_null
136
+ end
137
+
138
+ resolve_schema(prop_schema, schemas, visited)
139
+ end
140
+
141
+ def map_type(schema, schemas = {}, visited = Set.new)
142
+ resolved, next_visited = resolve_schema(schema, schemas, visited)
143
+ explicit = resolved["type"]
144
+ return explicit if %w[integer number boolean array object string].include?(explicit)
145
+
146
+ props, = collect_object_schema(resolved, schemas, next_visited)
147
+ return "object" if props.any?
148
+
149
+ Array(resolved["allOf"]).each do |sub|
150
+ sub_type = map_type(sub, schemas, next_visited)
151
+ return sub_type if %w[integer number boolean array object string].include?(sub_type)
152
+ end
153
+
154
+ "string"
155
+ end
156
+ end
157
+ end
158
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "set"
5
+ require_relative "open_api_schema_converter"
6
+
7
+ module Hooktrace
8
+ module Importers
9
+ class PaypalOpenApi
10
+ DEFAULT_SPEC_BASE = "https://raw.githubusercontent.com/paypal/paypal-rest-api-specifications/main/openapi"
11
+ DEFAULT_MAX_DEPTH = 2
12
+ ENVELOPE_REQUIRED = %w[id event_version create_time resource_type event_type resource].freeze
13
+
14
+ EVENT_RESOURCE_MAP = {
15
+ "PAYMENT.CAPTURE.COMPLETED" => ["payments_payment_v2.json", "capture"],
16
+ "PAYMENT.CAPTURE.DENIED" => ["payments_payment_v2.json", "capture"],
17
+ "PAYMENT.CAPTURE.PENDING" => ["payments_payment_v2.json", "capture"],
18
+ "PAYMENT.CAPTURE.REFUNDED" => ["payments_payment_v2.json", "refund"],
19
+ "PAYMENT.AUTHORIZATION.CREATED" => ["payments_payment_v2.json", "authorization"],
20
+ "PAYMENT.AUTHORIZATION.VOIDED" => ["payments_payment_v2.json", "authorization"],
21
+ "CHECKOUT.ORDER.APPROVED" => ["checkout_orders_v2.json", "order"],
22
+ "CHECKOUT.ORDER.COMPLETED" => ["checkout_orders_v2.json", "order"],
23
+ "CHECKOUT.ORDER.SAVED" => ["checkout_orders_v2.json", "order"],
24
+ "BILLING.SUBSCRIPTION.ACTIVATED" => ["billing_subscriptions_v1.json", "subscription"],
25
+ "BILLING.SUBSCRIPTION.CANCELLED" => ["billing_subscriptions_v1.json", "subscription"],
26
+ "BILLING.SUBSCRIPTION.CREATED" => ["billing_subscriptions_v1.json", "subscription"],
27
+ "BILLING.SUBSCRIPTION.SUSPENDED" => ["billing_subscriptions_v1.json", "subscription"],
28
+ "BILLING.SUBSCRIPTION.UPDATED" => ["billing_subscriptions_v1.json", "subscription"],
29
+ "INVOICING.INVOICE.CANCELLED" => ["invoicing_v2.json", "invoice"],
30
+ "INVOICING.INVOICE.CREATED" => ["invoicing_v2.json", "invoice"],
31
+ "INVOICING.INVOICE.PAID" => ["invoicing_v2.json", "invoice"],
32
+ "CUSTOMER.DISPUTE.CREATED" => ["customer_disputes_v1.json", "dispute"],
33
+ "CUSTOMER.DISPUTE.RESOLVED" => ["customer_disputes_v1.json", "dispute"],
34
+ "CUSTOMER.DISPUTE.UPDATED" => ["customer_disputes_v1.json", "dispute"]
35
+ }.freeze
36
+
37
+ def self.sync(output_path:, spec_base: DEFAULT_SPEC_BASE, events: nil, max_depth: DEFAULT_MAX_DEPTH)
38
+ new(spec_base: spec_base, events: events, max_depth: max_depth).sync(output_path: output_path)
39
+ end
40
+
41
+ def initialize(spec_base: DEFAULT_SPEC_BASE, events: nil, max_depth: DEFAULT_MAX_DEPTH)
42
+ @spec_base = spec_base.to_s.sub(%r{/+\z}, "")
43
+ @events = events
44
+ @converter = OpenApiSchemaConverter.new(max_depth: max_depth)
45
+ @spec_cache = {}
46
+ end
47
+
48
+ def generate_bundle
49
+ webhooks_spec = load_spec_file("notifications_webhooks_v1.json")
50
+ webhooks_schemas = webhooks_spec.fetch("components", {}).fetch("schemas", {})
51
+ event_schema = webhooks_schemas.fetch("event") do
52
+ raise Hooktrace::StandardError, "Missing 'event' schema in PayPal notifications_webhooks_v1.json"
53
+ end
54
+
55
+ base_fields = @converter.build_fields(
56
+ event_schema, webhooks_schemas,
57
+ depth: 0, visited: Set.new(["event"]), extra_required: ENVELOPE_REQUIRED
58
+ )
59
+ event_entries = [{ "name" => "event.base", "fields" => base_fields }]
60
+
61
+ selected_events.each do |event_name, (file_name, schema_name)|
62
+ event_entries << build_event_entry(event_name, base_fields, file_name, schema_name)
63
+ end
64
+
65
+ {
66
+ "provider" => "paypal",
67
+ "api_version" => webhooks_spec.dig("info", "version"),
68
+ "events" => event_entries
69
+ }
70
+ end
71
+
72
+ def sync(output_path:)
73
+ bundle = generate_bundle
74
+ File.write(output_path, "#{JSON.pretty_generate(bundle)}\n", encoding: "UTF-8")
75
+ bundle
76
+ end
77
+
78
+ private
79
+
80
+ def selected_events
81
+ return EVENT_RESOURCE_MAP.sort_by(&:first) if @events.nil? || @events == :all
82
+
83
+ allow = @events.map(&:to_s)
84
+ EVENT_RESOURCE_MAP.slice(*allow).sort_by(&:first)
85
+ end
86
+
87
+ def build_event_entry(event_name, base_fields, file_name, schema_name)
88
+ spec = load_spec_file(file_name)
89
+ schemas = spec.fetch("components", {}).fetch("schemas", {})
90
+ resource_schema = schemas[schema_name]
91
+
92
+ resource_fields = if resource_schema
93
+ @converter.build_fields(
94
+ resource_schema, schemas,
95
+ depth: 1, visited: Set.new([schema_name]), extra_required: ["id"]
96
+ )
97
+ else
98
+ []
99
+ end
100
+
101
+ fields = base_fields.map do |field|
102
+ field["name"] == "resource" ? field.merge("fields" => resource_fields) : field
103
+ end
104
+
105
+ { "name" => event_name, "fields" => fields }
106
+ end
107
+
108
+ def load_spec_file(file_name)
109
+ @spec_cache[file_name] ||= OpenApiSchemaConverter.load_spec("#{@spec_base}/#{file_name}")
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "set"
5
+ require_relative "open_api_schema_converter"
6
+
7
+ module Hooktrace
8
+ module Importers
9
+ class StripeOpenApi
10
+ DEFAULT_SPEC_URL = "https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.sdk.json"
11
+ DEFAULT_MAX_DEPTH = 2
12
+
13
+ CORE_EVENTS = %w[
14
+ charge.captured
15
+ charge.dispute.created
16
+ charge.failed
17
+ charge.refunded
18
+ charge.succeeded
19
+ charge.updated
20
+ checkout.session.completed
21
+ checkout.session.expired
22
+ customer.created
23
+ customer.deleted
24
+ customer.subscription.created
25
+ customer.subscription.deleted
26
+ customer.subscription.updated
27
+ customer.updated
28
+ invoice.created
29
+ invoice.finalized
30
+ invoice.paid
31
+ invoice.payment_failed
32
+ payment_intent.canceled
33
+ payment_intent.created
34
+ payment_intent.payment_failed
35
+ payment_intent.processing
36
+ payment_intent.requires_action
37
+ payment_intent.succeeded
38
+ payment_method.attached
39
+ payment_method.detached
40
+ payout.created
41
+ payout.failed
42
+ payout.paid
43
+ refund.created
44
+ refund.failed
45
+ ].freeze
46
+
47
+ def self.sync(output_path:, spec_source: DEFAULT_SPEC_URL, events: CORE_EVENTS, max_depth: DEFAULT_MAX_DEPTH)
48
+ new(spec_source: spec_source, events: events, max_depth: max_depth).sync(output_path: output_path)
49
+ end
50
+
51
+ def initialize(spec_source: DEFAULT_SPEC_URL, events: CORE_EVENTS, max_depth: DEFAULT_MAX_DEPTH)
52
+ @spec_source = spec_source
53
+ @events = events
54
+ @converter = OpenApiSchemaConverter.new(max_depth: max_depth)
55
+ end
56
+
57
+ def generate_bundle
58
+ spec = OpenApiSchemaConverter.load_spec(@spec_source)
59
+ schemas = spec.fetch("components", {}).fetch("schemas", {})
60
+ event_schema = schemas.fetch("event") do
61
+ raise Hooktrace::StandardError, "Missing 'event' schema in Stripe OpenAPI spec"
62
+ end
63
+
64
+ base_fields = @converter.build_fields(event_schema, schemas, depth: 0, visited: Set.new(["event"]))
65
+ event_entries = [{ "name" => "event.base", "fields" => base_fields }]
66
+
67
+ select_event_schemas(schemas).each do |event_name, schema|
68
+ object_ref = schema.dig("properties", "data", "properties", "object") || schema.dig("properties", "object")
69
+ event_fields = build_event_fields(base_fields, object_ref, schemas)
70
+ event_entries << { "name" => event_name, "fields" => event_fields }
71
+ end
72
+
73
+ {
74
+ "provider" => "stripe",
75
+ "api_version" => spec.dig("info", "version"),
76
+ "events" => event_entries
77
+ }
78
+ end
79
+
80
+ def sync(output_path:)
81
+ bundle = generate_bundle
82
+ File.write(output_path, "#{JSON.pretty_generate(bundle)}\n", encoding: "UTF-8")
83
+ bundle
84
+ end
85
+
86
+ private
87
+
88
+ def select_event_schemas(schemas)
89
+ all_events = schemas.select { |_, s| s.is_a?(Hash) && s.key?("x-stripeEvent") }
90
+ filtered = if @events == :all || @events.nil?
91
+ all_events
92
+ else
93
+ allow = @events.map(&:to_s)
94
+ all_events.slice(*allow)
95
+ end
96
+ filtered.sort_by(&:first)
97
+ end
98
+
99
+ def build_event_fields(base_fields, object_schema_ref, schemas)
100
+ object_fields = if object_schema_ref
101
+ @converter.build_fields(object_schema_ref, schemas, depth: 1, visited: Set.new)
102
+ else
103
+ []
104
+ end
105
+
106
+ base_fields.map do |field|
107
+ next field unless field["name"] == "data"
108
+
109
+ updated_data_children = (field["fields"] || []).map do |child|
110
+ child["name"] == "object" ? child.merge("fields" => object_fields) : child
111
+ end
112
+
113
+ field.merge("fields" => updated_data_children)
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Hooktrace
6
+ class Result
7
+ attr_reader :errors
8
+
9
+ def initialize(errors: [])
10
+ @errors = errors.freeze
11
+ freeze
12
+ end
13
+
14
+ def valid?
15
+ @errors.empty?
16
+ end
17
+
18
+ def invalid?
19
+ !valid?
20
+ end
21
+
22
+ def to_h
23
+ {
24
+ valid: valid?,
25
+ error_count: errors.size,
26
+ errors: errors.map(&:to_h)
27
+ }
28
+ end
29
+
30
+ def to_json(*args)
31
+ JSON.generate(to_h, *args)
32
+ end
33
+
34
+ def inspect
35
+ "#<#{self.class.name} valid=#{valid?} errors=#{errors.size}>"
36
+ end
37
+ end
38
+ end