spree_api 6.0.3 → 6.0.5

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 (70) hide show
  1. checksums.yaml +4 -4
  2. data/Rakefile +3 -5
  3. data/app/controllers/concerns/spree/api/v3/idempotent.rb +10 -1
  4. data/app/controllers/concerns/spree/api/v3/security_headers.rb +3 -0
  5. data/app/controllers/concerns/spree/api/v3/storefront_gating.rb +4 -2
  6. data/app/controllers/spree/api/v3/admin/base_controller.rb +31 -0
  7. data/app/controllers/spree/api/v3/admin/categories_controller.rb +1 -1
  8. data/app/controllers/spree/api/v3/admin/companies/memberships_controller.rb +21 -4
  9. data/app/controllers/spree/api/v3/admin/diagnostics_controller.rb +46 -0
  10. data/app/controllers/spree/api/v3/admin/me_controller.rb +0 -13
  11. data/app/controllers/spree/api/v3/admin/media_controller.rb +10 -0
  12. data/app/controllers/spree/api/v3/admin/orders/items_controller.rb +6 -2
  13. data/app/controllers/spree/api/v3/admin/sellers/invitations_controller.rb +39 -3
  14. data/app/controllers/spree/api/v3/admin/sellers/team_controller.rb +1 -3
  15. data/app/controllers/spree/api/v3/admin/sellers_controller.rb +24 -1
  16. data/app/controllers/spree/api/v3/admin/stock_levels_controller.rb +15 -1
  17. data/app/controllers/spree/api/v3/admin/store_controller.rb +9 -1
  18. data/app/controllers/spree/api/v3/admin/updates_controller.rb +4 -15
  19. data/app/controllers/spree/api/v3/seller/option_types_controller.rb +41 -0
  20. data/app/controllers/spree/api/v3/seller/products/media_controller.rb +46 -0
  21. data/app/controllers/spree/api/v3/seller/products_controller.rb +39 -2
  22. data/app/controllers/spree/api/v3/seller/profile_controller.rb +13 -5
  23. data/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb +7 -3
  24. data/app/controllers/spree/api/v3/store/carts_controller.rb +11 -8
  25. data/app/controllers/spree/api/v3/store/categories_controller.rb +1 -1
  26. data/app/controllers/spree/api/v3/store/companies/addresses_controller.rb +1 -1
  27. data/app/controllers/spree/api/v3/store/store_controller.rb +3 -2
  28. data/app/request_schemas/spree/api/v3/seller/variant_request_schema.rb +4 -0
  29. data/app/request_schemas/spree/api/v3/store/address_request_schema.rb +2 -2
  30. data/app/serializers/spree/api/v3/address_serializer.rb +3 -3
  31. data/app/serializers/spree/api/v3/admin/address_serializer.rb +1 -1
  32. data/app/serializers/spree/api/v3/admin/company_membership_serializer.rb +4 -0
  33. data/app/serializers/spree/api/v3/admin/diagnostics_serializer.rb +30 -0
  34. data/app/serializers/spree/api/v3/admin/line_item_serializer.rb +6 -1
  35. data/app/serializers/spree/api/v3/admin/market_serializer.rb +1 -1
  36. data/app/serializers/spree/api/v3/admin/refund_serializer.rb +1 -1
  37. data/app/serializers/spree/api/v3/admin/seller_serializer.rb +10 -0
  38. data/app/serializers/spree/api/v3/admin/stock_location_serializer.rb +1 -1
  39. data/app/serializers/spree/api/v3/admin/store_serializer.rb +0 -7
  40. data/app/serializers/spree/api/v3/base_serializer.rb +1 -1
  41. data/app/serializers/spree/api/v3/cart_serializer.rb +4 -3
  42. data/app/serializers/spree/api/v3/country_serializer.rb +1 -1
  43. data/app/serializers/spree/api/v3/currency_serializer.rb +3 -2
  44. data/app/serializers/spree/api/v3/locale_serializer.rb +1 -1
  45. data/app/serializers/spree/api/v3/market_serializer.rb +2 -2
  46. data/app/serializers/spree/api/v3/price_history_serializer.rb +1 -1
  47. data/app/serializers/spree/api/v3/price_serializer.rb +2 -2
  48. data/app/serializers/spree/api/v3/product_category_serializer.rb +26 -0
  49. data/app/serializers/spree/api/v3/product_collection_serializer.rb +26 -0
  50. data/app/serializers/spree/api/v3/refund_serializer.rb +2 -2
  51. data/app/serializers/spree/api/v3/seller/address_serializer.rb +1 -1
  52. data/app/serializers/spree/api/v3/seller/option_type_serializer.rb +18 -0
  53. data/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb +2 -2
  54. data/app/serializers/spree/api/v3/seller/product_serializer.rb +1 -1
  55. data/app/serializers/spree/api/v3/seller/product_type_serializer.rb +8 -7
  56. data/app/serializers/spree/api/v3/seller/stock_location_serializer.rb +1 -1
  57. data/app/serializers/spree/api/v3/stock_location_serializer.rb +3 -3
  58. data/app/serializers/spree/api/v3/store_serializer.rb +17 -5
  59. data/app/services/spree/api/v3/request_schema.rb +1 -1
  60. data/config/routes.rb +9 -2
  61. data/lib/spree/api/agent_resource_map.rb +42 -7
  62. data/lib/spree/api/dependencies.rb +6 -6
  63. data/lib/spree/api/oauth.rb +8 -19
  64. data/lib/spree/api/openapi/path_sorter.rb +91 -74
  65. data/lib/spree/api/testing_support/openapi.rb +2 -1
  66. data/lib/spree/api/testing_support/sdk_method.rb +34 -0
  67. data/lib/spree/api/typelizer_generation.rb +1 -1
  68. data/openapi/admin.yaml +34498 -34007
  69. data/openapi/store.yaml +9144 -9102
  70. metadata +14 -6
@@ -13,7 +13,7 @@ module Spree
13
13
  class OrderLineItemSerializer < V3::BaseSerializer
14
14
  typelize name: :string, sku: [:string, nullable: true], options_text: [:string, nullable: true],
15
15
  quantity: :number, currency: [:string, enum: Spree::Money::Rounding::CURRENCY_CODES, enum_type_name: 'CurrencyCode'], variant_id: [:string, nullable: true],
16
- thumbnail_url: [:string, nullable: true]
16
+ thumbnail_url: [:string, nullable: true], product_id: [:string, nullable: true]
17
17
 
18
18
  attributes :name, :options_text, :quantity, :currency
19
19
 
@@ -22,7 +22,7 @@ module Spree
22
22
  money_attributes :discounted_amount,
23
23
  :additional_tax_total, :total
24
24
 
25
- prefixed_id_attributes :variant
25
+ prefixed_id_attributes :variant, :product
26
26
 
27
27
  # How a seller finds the item on their own shelf.
28
28
  attribute :sku do |line_item|
@@ -46,7 +46,7 @@ module Spree
46
46
  if: proc { expand?('media') }
47
47
 
48
48
  many :option_types,
49
- resource: proc { Spree.api.option_type_serializer },
49
+ resource: proc { Spree.api.seller_option_type_serializer },
50
50
  if: proc { expand?('option_types') }
51
51
 
52
52
  # Why the marketplace sent this back, so the panel can show it
@@ -5,19 +5,20 @@ module Spree
5
5
  # A product type as a seller sees it: something to list against, and
6
6
  # what picking it will bring.
7
7
  #
8
- # The option types are carried as **labels**, not as ids the client
9
- # then resolves. The operator's form looks them up against the option
10
- # types page it already loads, but a seller manages no option-type
11
- # vocabulary and has no such endpoint — sending ids alone would leave
12
- # the form unable to name them, and the warning it exists to show
13
- # would silently never appear.
8
+ # `option_type_ids` is what the variants builder offers as rows on a
9
+ # new product, resolved against `GET /seller/option_types`. The labels
10
+ # are sent as well, already named, so the form can warn which options
11
+ # the type adds without waiting on that list.
14
12
  #
15
13
  # No `category_ids` (filing is the operator's, so a seller would be
16
14
  # shown a consequence they never see) and no `products_count` or
17
15
  # custom field schema, which describe how the operator maintains the
18
16
  # type rather than what listing against it does.
19
17
  class ProductTypeSerializer < V3::ProductTypeSerializer
20
- typelize option_type_labels: [:string, multi: true]
18
+ typelize option_type_ids: [:string, multi: true],
19
+ option_type_labels: [:string, multi: true]
20
+
21
+ attribute :option_type_ids, &:option_type_prefixed_ids
21
22
 
22
23
  attribute :option_type_labels do |product_type|
23
24
  product_type.option_types.map { |option_type| option_type.label.presence || option_type.name }.compact
@@ -3,7 +3,7 @@ module Spree
3
3
  module V3
4
4
  module Seller
5
5
  class StockLocationSerializer < V3::StockLocationSerializer
6
- # The Store API keeps these deprecated names until 6.1.
6
+ # The Store API keeps these deprecated names until 6.5.
7
7
  %i[country_iso state_abbr].each { |key| _attributes.delete(key) }
8
8
 
9
9
  typelize address2: [:string, nullable: true], state_name: [:string, nullable: true],
@@ -6,15 +6,15 @@ module Spree
6
6
  zipcode: [:string, nullable: true], country_code: [:string, nullable: true, enum: Spree::IsoData.country_codes, enum_type_name: 'CountryCode'],
7
7
  country_name: [:string, nullable: true], state_code: [:string, nullable: true],
8
8
  state_text: [:string, nullable: true],
9
- country_iso: [:string, nullable: true, deprecated: 'Use `country_code`. Removed in 6.1.'],
10
- state_abbr: [:string, nullable: true, deprecated: 'Use `state_code`. Removed in 6.1.'],
9
+ country_iso: [:string, nullable: true, deprecated: 'Use `country_code`. Removed in 6.5.'],
10
+ state_abbr: [:string, nullable: true, deprecated: 'Use `state_code`. Removed in 6.5.'],
11
11
  pickup_ready_in_minutes: [:number, nullable: true],
12
12
  pickup_instructions: [:string, nullable: true]
13
13
 
14
14
  attributes :name, :address1, :city, :zipcode, :country_code, :country_name, :state_code, :state_text
15
15
 
16
16
  # @deprecated Storefronts shipped against these names; use +country_code+
17
- # and +state_code+. Removed in 6.1.
17
+ # and +state_code+. Removed in 6.5.
18
18
  attribute :country_iso, &:country_code
19
19
  attribute :state_abbr, &:state_code
20
20
 
@@ -1,15 +1,27 @@
1
1
  module Spree
2
2
  module Api
3
3
  module V3
4
- # The current store's public identity and default SEO metadata, in the
5
- # request's locale. Missing translations fall back to the store's default
6
- # locale.
4
+ # The current store's public identity, branding and default SEO metadata,
5
+ # in the request's locale. Missing translations fall back to the store's
6
+ # default locale.
7
7
  class StoreSerializer < BaseSerializer
8
8
  typelize name: :string,
9
9
  seo_title: [:string, nullable: true],
10
- meta_description: [:string, nullable: true]
10
+ meta_description: [:string, nullable: true],
11
+ meta_keywords: [:string, nullable: true],
12
+ logo_url: [:string, nullable: true],
13
+ facebook: [:string, nullable: true, comment: 'Facebook page, as entered by the merchant: a handle or a full URL.'],
14
+ twitter: [:string, nullable: true, comment: 'X (Twitter) account, as entered by the merchant: a handle or a full URL.'],
15
+ instagram: [:string, nullable: true, comment: 'Instagram account, as entered by the merchant: a handle or a full URL.'],
16
+ customer_support_email: [:string, nullable: true]
11
17
 
12
- attributes :name, :seo_title, :meta_description
18
+ attributes :name, :seo_title, :meta_description, :meta_keywords,
19
+ :facebook, :twitter, :instagram,
20
+ :customer_support_email
21
+
22
+ attribute :logo_url do |store|
23
+ image_url_for(store.logo)
24
+ end
13
25
  end
14
26
  end
15
27
  end
@@ -23,7 +23,7 @@ module Spree
23
23
  # creating only. `only: :create` (or `:update`) accepts the field on one
24
24
  # action alone. `permit: false` documents a field the controller reads
25
25
  # from the raw params itself. `format:` documents a string's format
26
- # (`email`, `uri`). `deprecated: 'Use country_code. Removed in 6.1.'`
26
+ # (`email`, `uri`). `deprecated: 'Use country_code. Removed in 6.5.'`
27
27
  # keeps a field working while the API reference and the SDK types flag it.
28
28
  class RequestSchema
29
29
  KINDS = {
data/config/routes.rb CHANGED
@@ -162,7 +162,7 @@ Spree::Core::Engine.add_routes do
162
162
  # customer's own request names, for the same reason.
163
163
  get 'data_requests/:token', to: 'data_requests#show', as: :data_request
164
164
  post 'data_requests/:token/confirmation', to: 'data_request_confirmations#create', as: :data_request_confirmation
165
- # Legacy path — emailed and bookmarked URLs outlive the rename. Removed in 6.1.
165
+ # Legacy path — emailed and bookmarked URLs outlive the rename. Removed in 6.5.
166
166
  get 'digitals/:token', to: 'digital_links#show', as: :digital_download
167
167
 
168
168
  # Data Feeds (public, no auth required)
@@ -285,6 +285,7 @@ Spree::Core::Engine.add_routes do
285
285
  patch 'me', to: 'me#update'
286
286
 
287
287
  resource :updates, only: :show
288
+ resource :diagnostics, only: :show
288
289
 
289
290
  # Store Settings
290
291
  resource :store, only: [:show, :update], controller: 'store' do
@@ -610,7 +611,7 @@ Spree::Core::Engine.add_routes do
610
611
  # The operator is the only one who can repair a seller whose team
611
612
  # has locked itself out, which the seller's own panel cannot do.
612
613
  resources :team, only: [:index, :destroy], controller: 'sellers/team'
613
- resources :invitations, only: [:index, :destroy], controller: 'sellers/invitations' do
614
+ resources :invitations, only: [:index, :create, :destroy], controller: 'sellers/invitations' do
614
615
  patch :resend, on: :member
615
616
  resource :acceptance_link, only: [:show], controller: 'sellers/invitations/acceptance_links'
616
617
  end
@@ -930,6 +931,7 @@ Spree::Core::Engine.add_routes do
930
931
 
931
932
  resources :digital_assets, controller: 'products/digital_assets',
932
933
  only: [:index, :create, :show, :update, :destroy]
934
+ resources :media, controller: 'products/media', only: [:destroy]
933
935
  end
934
936
 
935
937
 
@@ -1043,6 +1045,11 @@ Spree::Core::Engine.add_routes do
1043
1045
  # the operator's (docs/plans/6.0-seller-product-submission.md).
1044
1046
  resources :product_types, only: [:index, :show]
1045
1047
 
1048
+ # The option types and values a seller builds variants from. Read
1049
+ # only: the vocabulary is the operator's, the variants are the seller's
1050
+ # (docs/plans/6.0-multi-vendor-marketplace.md).
1051
+ resources :option_types, only: [:index, :show]
1052
+
1046
1053
  # The marketplace's delivery vocabulary, for the product form's picker.
1047
1054
  # Read only: a seller assigns a profile, never creates one
1048
1055
  # (docs/plans/6.0-multi-vendor-marketplace.md, Decision 13).
@@ -71,16 +71,23 @@ module Spree
71
71
  # one, because the scope belongs to the resource being imported or
72
72
  # exported — creating a product import is a product write, and reading
73
73
  # its rows exposes the uploaded data. A single static key cannot say
74
- # that, so these are registered read-only under the broadest key the
75
- # controller can demand, and the write path stays with the endpoint.
74
+ # that, so these open to a caller holding the scope of any one type,
75
+ # in the kind the controller asks for: `read_` for an export, `write_`
76
+ # for an import. The endpoint then keeps to the types that key covers.
77
+ #
78
+ # Creating one stays with create_import and create_export; reading,
79
+ # listing and deleting go to the endpoint.
76
80
  DYNAMIC_SCOPE_RESOURCES = {
77
- 'imports' => { model_name: 'Spree::Import', permission: 'read_settings',
81
+ 'imports' => { model_name: 'Spree::Import', access_kind: 'write',
78
82
  serializer_name: 'Spree::Api::V3::Admin::ImportSerializer',
79
83
  dashboard_path: '/settings/imports' },
80
- 'exports' => { model_name: 'Spree::Export', permission: 'read_settings',
84
+ 'exports' => { model_name: 'Spree::Export', access_kind: 'read',
81
85
  serializer_name: 'Spree::Api::V3::Admin::ExportSerializer' }
82
86
  }.freeze
83
87
 
88
+ # The operations the generic tools reach on those resources.
89
+ DYNAMIC_SCOPE_ACTIONS = %i[index show destroy].freeze
90
+
84
91
  class << self
85
92
  # Registers this walk as how the core map fills itself, and marks the
86
93
  # map stale so the next reader gets a fresh one. Called on every code
@@ -102,7 +109,11 @@ module Spree
102
109
  registered = resolve_collisions(controllers.filter_map { |controller| derive(controller) })
103
110
  registered.each { |entry| map.register(**entry) }
104
111
 
105
- DYNAMIC_SCOPE_RESOURCES.each { |key, attributes| map.register(key: key, **attributes) }
112
+ DYNAMIC_SCOPE_RESOURCES.each do |key, attributes|
113
+ map.register(key: key, permission: nil, **attributes.except(:access_kind),
114
+ api_paths: dynamic_scope_paths(attributes[:model_name]),
115
+ access_permissions: type_permissions(attributes[:model_name], attributes[:access_kind]))
116
+ end
106
117
 
107
118
  registered.size + DYNAMIC_SCOPE_RESOURCES.size
108
119
  end
@@ -183,6 +194,7 @@ module Spree
183
194
  create_workflow = workflow_key(instance, :create_workflow)
184
195
  update_workflow = workflow_key(instance, :update_workflow)
185
196
  writable = AgentWriteSchemas.attribute_names(key)
197
+ api_paths = api_paths_for(controller)
186
198
 
187
199
  {
188
200
  key: key,
@@ -190,7 +202,8 @@ module Spree
190
202
  permission: "read_#{scope}",
191
203
  serializer_name: serializer.name,
192
204
  dashboard_path: DASHBOARD_PATHS[key],
193
- api_paths: api_paths_for(controller),
205
+ api_paths: api_paths,
206
+ index_paths: Array(api_paths[:index]),
194
207
  write_permission: write_permission_for(model, scope, create_workflow, update_workflow, writable, controller),
195
208
  writable_attributes: writable,
196
209
  create_workflow_key: create_workflow,
@@ -219,6 +232,25 @@ module Spree
219
232
 
220
233
  private
221
234
 
235
+ # The read and delete paths of the controller serving an import or
236
+ # export. Without them the generic tools refused every one, though
237
+ # create_export tells the agent to read the export with get_resource.
238
+ def dynamic_scope_paths(model_name)
239
+ controller = controllers.find { |candidate| model_for(candidate)&.name == model_name }
240
+ return {} if controller.nil?
241
+
242
+ api_paths_for(controller).slice(*DYNAMIC_SCOPE_ACTIONS)
243
+ end
244
+
245
+ # The catalog keys that open an import or export of each registered
246
+ # type. A type with no scope of its own needs `read_all` or
247
+ # `write_all`, which no catalog key stands for, so it adds none.
248
+ def type_permissions(model_name, kind)
249
+ model_name.constantize.available_types.
250
+ filter_map { |type| type.required_scope.presence && "#{kind}_#{type.required_scope}" }.
251
+ uniq.select { |key| Spree.permissions.key?(key) }
252
+ end
253
+
222
254
  # What the controller does with its own collection. A controller that
223
255
  # disables DISTINCT has a reason — Postgres refuses it beside an
224
256
  # ORDER BY the select list does not carry — and a search tool adding
@@ -273,7 +305,10 @@ module Spree
273
305
  # nothing about depth — so a resource served both at the top
274
306
  # level and under a parent kept whichever won on scope, and a
275
307
  # tool was handed a path with an unfillable `:parent_id` in it.
276
- api_paths: shallowest_paths(candidates)
308
+ api_paths: shallowest_paths(candidates),
309
+ # Every collection path, not only the shallowest, so a search
310
+ # under a parent reaches the controller that lists its records.
311
+ index_paths: candidates.flat_map { |entry| entry[:index_paths] }.uniq
277
312
  )
278
313
  end
279
314
  end
@@ -38,7 +38,7 @@ module Spree
38
38
  channel order_routing_rule product_publication market delivery_method delivery_method_service
39
39
  stock_location stock_reservation delivery_rate freight_summary freight_summary_line payment_method
40
40
  credit_card store_credit store_credit_event customer_group payment_source digital_asset digital_link
41
- store setup_task update_status api_key oauth_application oauth_access_token oauth_consent_request oauth_redirect
41
+ store setup_task update_status diagnostics api_key oauth_application oauth_access_token oauth_consent_request oauth_redirect
42
42
  oauth_protected_resource allowed_origin webhook_endpoint webhook_event webhook_delivery invitation
43
43
  invitation_acceptance_link role permission export saved_report import import_row import_mapping promotion
44
44
  maintenance_task_run
@@ -48,7 +48,7 @@ module Spree
48
48
 
49
49
  SELLER_SERIALIZERS =
50
50
  %i[address country state profile policy team_member account invitation invitation_acceptance_link product product_type
51
- delivery_profile delivery_method delivery_method_rule delivery_zone variant media stock_level order
51
+ option_type delivery_profile delivery_method delivery_method_rule delivery_zone variant media stock_level order
52
52
  order_line_item fulfillment fulfillment_item delivery delivery_rate shipping_label return
53
53
  return_line_item exchange exchange_line_item claim claim_line_item reason package_type stock_location
54
54
  requirement_custom_field tax_identifier requirement_status import import_row import_mapping
@@ -75,7 +75,7 @@ module Spree
75
75
  # legacy workflow keys in core, these forward instead of stashing: a
76
76
  # serializer renders the same model under a new class name, so an
77
77
  # override written against the old key is still the class the host app
78
- # wants used. Removed in 6.1.
78
+ # wants used. Removed in 6.3.
79
79
  LEGACY_SERIALIZER_KEYS = {
80
80
  stock_item_serializer: :stock_level_serializer,
81
81
  admin_stock_item_serializer: :admin_stock_level_serializer,
@@ -85,17 +85,17 @@ module Spree
85
85
 
86
86
  LEGACY_SERIALIZER_KEYS.each do |legacy, current|
87
87
  define_method("#{legacy}=") do |value|
88
- Spree::Deprecation.warn("Spree.api.#{legacy}= is deprecated and will be removed in Spree 6.1. Use #{current}= instead.")
88
+ Spree::Deprecation.warn("Spree.api.#{legacy}= is deprecated and will be removed in Spree 6.3. Use #{current}= instead.")
89
89
  send("#{current}=", value)
90
90
  end
91
91
 
92
92
  define_method(legacy) do
93
- Spree::Deprecation.warn("Spree.api.#{legacy} is deprecated and will be removed in Spree 6.1. Use #{current} instead.")
93
+ Spree::Deprecation.warn("Spree.api.#{legacy} is deprecated and will be removed in Spree 6.3. Use #{current} instead.")
94
94
  send(current)
95
95
  end
96
96
 
97
97
  define_method("#{legacy}_class") do
98
- Spree::Deprecation.warn("Spree.api.#{legacy}_class is deprecated and will be removed in Spree 6.1. Use #{current}_class instead.")
98
+ Spree::Deprecation.warn("Spree.api.#{legacy}_class is deprecated and will be removed in Spree 6.3. Use #{current}_class instead.")
99
99
  send("#{current}_class")
100
100
  end
101
101
  end
@@ -15,41 +15,30 @@ module Spree
15
15
  # which is why this lives in `spree_api` rather than in any one gem that
16
16
  # happens to need it.
17
17
  module Oauth
18
- # Whether a redirect URI points at the machine the client runs on, by IP
19
- # literal (`127.0.0.1`, `[::1]`).
20
- #
21
- # Decided by parsing the host as an address, the same way Doorkeeper
22
- # does when it ignores the port of a loopback redirect.
18
+ # Whether a redirect URI points at the machine the client runs on: an IP
19
+ # literal (`127.0.0.1`, `[::1]`) or `localhost`. Doorkeeper ignores the
20
+ # port of exactly these (RFC 8252 §7.3), and matches `localhost` only in
21
+ # lowercase.
23
22
  #
24
23
  # @param uri [URI, String]
25
24
  # @return [Boolean]
26
25
  def self.loopback_uri?(uri)
27
26
  host = uri.respond_to?(:host) ? uri.host : URI.parse(uri.to_s).host
28
27
  return false if host.blank?
28
+ return true if host == 'localhost'
29
29
 
30
30
  IPAddr.new(host).loopback?
31
31
  rescue StandardError
32
32
  false
33
33
  end
34
34
 
35
- # Whether a redirect URI may use plain http: an IP-literal loopback, or
36
- # `localhost` with an explicit port.
37
- #
38
- # Claude Code only ever calls back on `http://localhost:<port>`. Doorkeeper
39
- # compares a `localhost` callback exactly, so the host must be lowercase
40
- # and the port explicit: anything else could never match an
41
- # authorization.
35
+ # Whether a redirect URI may use plain http: only a loopback one, which
36
+ # never leaves the machine.
42
37
  #
43
38
  # @param uri [URI, String]
44
39
  # @return [Boolean]
45
40
  def self.local_redirect_uri?(uri)
46
- uri = URI.parse(uri.to_s) unless uri.respond_to?(:host)
47
- return true if loopback_uri?(uri)
48
-
49
- uri.host == 'localhost' &&
50
- (1..65_535).cover?(uri.port) && uri.port != uri.default_port
51
- rescue StandardError
52
- false
41
+ loopback_uri?(uri)
53
42
  end
54
43
 
55
44
  # Protected resources, each registered by the surface that owns it as a
@@ -1,26 +1,29 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'yaml'
4
+
3
5
  module Spree
4
6
  module Api
5
7
  module OpenAPI
6
- # Reorders the `paths:` block of a generated OpenAPI YAML so paths are grouped
7
- # by tag, in the same order as the top-level `tags:` array.
8
+ # Orders a generated OpenAPI YAML for the Mintlify sidebar: Authentication
9
+ # first, every other tag alphabetical.
8
10
  #
9
- # rswag emits paths in the order specs are loaded (alphabetical by filename),
10
- # which doesn't match the curated `tags:` array order in swagger_helper.rb.
11
- # Mintlify groups sidebar sections by the *first appearance* of each tag in
12
- # `paths:` — so after this sort runs, the sidebar matches the `tags:` array.
11
+ # rswag emits paths in the order specs are loaded, and Mintlify renders one
12
+ # sidebar group per tag in the order tags first appear in `paths:`. So this
13
+ # reorders the `paths:` block by each path's primary tag, and rewrites the
14
+ # top-level `tags:` block in the same order, adding any tag an operation
15
+ # uses but swagger_helper.rb doesn't declare.
13
16
  #
14
17
  # The reorder is line-based to preserve the exact text formatting that
15
18
  # rswag/Psych produced (indentation, multi-line string wrapping, etc.).
16
19
  module PathSorter
20
+ FIRST_TAG = 'Authentication'
21
+
17
22
  module_function
18
23
 
19
- # Sort the `paths:` block in `path` so each path's first-operation primary
20
- # tag follows the order defined in the document's top-level `tags:` array.
21
24
  # Returns true if the file was rewritten, false if already sorted.
22
25
  def sort_file!(path)
23
- original = File.read(path)
26
+ original = File.read(path, encoding: Encoding::UTF_8)
24
27
  sorted = sort_text(original)
25
28
  return false if sorted == original
26
29
 
@@ -28,97 +31,111 @@ module Spree
28
31
  true
29
32
  end
30
33
 
31
- # Pure-string variant: sort a YAML document's `paths:` block by tag order.
32
34
  def sort_text(yaml)
33
35
  lines = yaml.lines
34
- tag_rank = extract_tag_rank(lines)
35
- return yaml if tag_rank.empty?
36
-
37
- paths_start = lines.index { |l| l.start_with?('paths:') }
38
- return yaml unless paths_start
39
36
 
40
- paths_end_exclusive = (paths_start + 1...lines.size).find do |i|
41
- line = lines[i]
42
- line.match?(/\A[A-Za-z]/) || line.start_with?('x-')
43
- end || lines.size
37
+ paths_range = block_range(lines, 'paths:')
38
+ return yaml unless paths_range
44
39
 
45
- blocks = collect_path_blocks(lines, paths_start + 1, paths_end_exclusive)
40
+ blocks = collect_path_blocks(lines, paths_range)
46
41
  return yaml if blocks.empty?
47
42
 
48
- unknown_rank = tag_rank.size
49
- sorted_blocks = blocks.each_with_index.sort_by do |block, original_index|
50
- [tag_rank.fetch(block[:tag], unknown_rank), original_index]
43
+ tags_range = block_range(lines, 'tags:')
44
+ tag_entries = tags_range ? collect_tag_entries(lines, tags_range) : {}
45
+ blocks.flat_map { |block| block[:tags] }.uniq.each do |name|
46
+ tag_entries[name] ||= YAML.dump([{ 'name' => name }]).delete_prefix("---\n")
47
+ end
48
+
49
+ order = tag_entries.keys.sort_by { |name| tag_sort_key(name) }
50
+ rank = order.each_with_index.to_h
51
+
52
+ sorted_blocks = blocks.each_with_index.sort_by do |block, index|
53
+ [rank.fetch(block[:tags].first, rank.size), index]
51
54
  end.map(&:first)
52
55
 
53
- prefix = lines[0..paths_start].join
54
- suffix = lines[paths_end_exclusive..].to_a.join
55
- prefix + sorted_blocks.map { |b| b[:text] }.join + suffix
56
+ replacements = { paths_range => sorted_blocks.sum('') { |block| block[:text] } }
57
+ replacements[tags_range] = order.map { |name| tag_entries[name] }.join if tags_range
58
+
59
+ replace_ranges(lines, replacements)
60
+ end
61
+
62
+ def tag_sort_key(name)
63
+ [name == FIRST_TAG ? 0 : 1, name.downcase]
64
+ end
65
+
66
+ # The body lines of a top-level key, as a range excluding the key itself.
67
+ def block_range(lines, key)
68
+ start = lines.index { |l| l.start_with?(key) }
69
+ return unless start
70
+
71
+ finish = ((start + 1)...lines.size).find { |i| top_level?(lines[i]) } || lines.size
72
+ (start + 1)...finish
73
+ end
74
+
75
+ def top_level?(line)
76
+ line.match?(/\A[A-Za-z]/) || line.start_with?('x-')
56
77
  end
57
78
 
58
- # Parse the top-level `tags:` block and return { tag_name => index } in
59
- # declared order. Returns {} if not found.
60
- def extract_tag_rank(lines)
61
- start = lines.index { |l| l.start_with?('tags:') }
62
- return {} unless start
79
+ def replace_ranges(lines, replacements)
80
+ out = +''
81
+ cursor = 0
82
+ replacements.sort_by { |range, _| range.begin }.each do |range, text|
83
+ out << lines[cursor...range.begin].join << text
84
+ cursor = range.end
85
+ end
86
+ out << lines[cursor..].to_a.join
87
+ end
63
88
 
64
- rank = {}
65
- i = start + 1
66
- while i < lines.size
89
+ # { tag_name => entry_text } in declared order.
90
+ def collect_tag_entries(lines, range)
91
+ entries = {}
92
+ current = nil
93
+ range.each do |i|
67
94
  line = lines[i]
68
95
  if line.start_with?('- name: ')
69
- rank[line.sub('- name: ', '').strip] = rank.size
70
- elsif line.match?(/\A[A-Za-z]/) || line.start_with?('x-')
71
- break
96
+ current = scalar(line.sub('- name: ', ''))
97
+ entries[current] = +''
72
98
  end
73
- i += 1
99
+ entries[current] << line if current
74
100
  end
75
- rank
101
+ entries
76
102
  end
77
103
 
78
- # Collect each path block as { tag:, text: } from lines[range].
79
- # A path block starts on a line beginning with two spaces + a quote.
80
- def collect_path_blocks(lines, start_idx, end_idx_exclusive)
81
- blocks = []
82
- current_start = nil
83
-
84
- (start_idx...end_idx_exclusive).each do |i|
85
- if path_header?(lines[i])
86
- blocks << build_block(lines, current_start, i) if current_start
87
- current_start = i
88
- end
104
+ # Each path block as { tags:, text: }, its first tag deciding its place.
105
+ # A block starts on a line beginning with two spaces and a slash,
106
+ # optionally quoted.
107
+ def collect_path_blocks(lines, range)
108
+ starts = range.select { |i| path_header?(lines[i]) }
109
+ starts.each_with_index.map do |from, idx|
110
+ to = starts[idx + 1] || range.end
111
+ slice = lines[from...to]
112
+ { tags: extract_tags(slice), text: slice.join }
89
113
  end
90
- blocks << build_block(lines, current_start, end_idx_exclusive) if current_start
91
-
92
- blocks
93
114
  end
94
115
 
95
116
  def path_header?(line)
96
117
  line.start_with?(' "/') || line.start_with?(' /')
97
118
  end
98
119
 
99
- def build_block(lines, from, to_exclusive)
100
- slice = lines[from...to_exclusive]
101
- {
102
- tag: extract_primary_tag(slice),
103
- text: slice.join
104
- }
105
- end
106
-
107
- # Within a path block, find the first `tags:` line and return the first
108
- # tag value following it (the path block's "primary" tag).
109
- def extract_primary_tag(slice)
110
- slice.each_with_index do |line, idx|
111
- next unless line.match?(/\A {6}tags:\s*$/)
112
-
113
- slice[(idx + 1)..].each do |next_line|
114
- if next_line.start_with?(' - ')
115
- value = next_line[8..].strip
116
- return value unless value.empty?
117
- end
118
- break if next_line.match?(/\A {0,4}\S/)
120
+ # Every operation's tags in a path block, in order.
121
+ def extract_tags(slice)
122
+ tags = []
123
+ in_tags = false
124
+ slice.each do |line|
125
+ if line.match?(/\A {6}tags:\s*$/)
126
+ in_tags = true
127
+ elsif in_tags && line.start_with?(' - ')
128
+ tags << scalar(line[8..])
129
+ else
130
+ in_tags = false
119
131
  end
120
132
  end
121
- nil
133
+ tags.uniq
134
+ end
135
+
136
+ # A YAML scalar as written by Psych, quotes and escapes included.
137
+ def scalar(text)
138
+ YAML.safe_load(text).to_s
122
139
  end
123
140
  end
124
141
  end
@@ -2,6 +2,7 @@ require 'spree/api/testing_support/v3/base'
2
2
  require 'spree/api/testing_support/agent_tools'
3
3
  require 'spree/api/testing_support/deterministic_openapi'
4
4
  require 'spree/api/testing_support/filter_parameters'
5
+ require 'spree/api/testing_support/sdk_method'
5
6
 
6
7
  module Spree
7
8
  module Api
@@ -165,7 +166,7 @@ module Spree
165
166
  # and in its Rakefile, `require 'spree/api/testing_support/openapi_tasks'`
166
167
  # for `rake spree:openapi:generate`.
167
168
  module Openapi
168
- HELPERS = [RequestBody, FilterParameters, AdminScope, AdminOperation, AgentTools].freeze
169
+ HELPERS = [RequestBody, FilterParameters, AdminScope, AdminOperation, AgentTools, SdkMethod].freeze
169
170
 
170
171
  class << self
171
172
  # @param config [RSpec::Core::Configuration]
@@ -0,0 +1,34 @@
1
+ module Spree
2
+ module Api
3
+ module TestingSupport
4
+ # rswag helper for what an operation is called in the SDK client
5
+ # `spree sdk generate` writes for an extension. By default a method is
6
+ # named after the path (`PATCH /quotes/{id}/send` → `quotes.send`), and
7
+ # an `operationId` renames it, but the `operationId` also names the
8
+ # operation's agent tool. This names the SDK method alone:
9
+ #
10
+ # delete 'Remove a file from a quote' do
11
+ # sdk_method :remove_attachment # quotes.removeAttachment
12
+ # end
13
+ #
14
+ # post 'Upload a file for a quote request' do
15
+ # sdk_method :presign_attachment, namespace: :quotes # not carts.…
16
+ # end
17
+ #
18
+ # See docs/plans/6.0-sdk-extensions.md.
19
+ module SdkMethod
20
+ METHOD_KEY = :'x-spree-sdk-method'
21
+ NAMESPACE_KEY = :'x-spree-sdk-namespace'
22
+
23
+ # @param name [Symbol, String] the method, snake_case or camelCase
24
+ # @param namespace [Symbol, String, nil] the client namespace it goes in,
25
+ # instead of the path's resource
26
+ # @return [void]
27
+ def sdk_method(name, namespace: nil)
28
+ metadata[:operation][METHOD_KEY] = name.to_s
29
+ metadata[:operation][NAMESPACE_KEY] = namespace.to_s if namespace
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end