skyward-api 0.1.0 → 0.2.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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +185 -47
  3. data/lib/skyward/api/assembly/application.rb +26 -0
  4. data/lib/skyward/api/assembly/boot.rb +533 -0
  5. data/lib/skyward/api/assembly/builder.rb +83 -0
  6. data/lib/skyward/api/assembly/dispatcher.rb +121 -0
  7. data/lib/skyward/api/assembly/static.rb +115 -0
  8. data/lib/skyward/api/assembly.rb +4 -0
  9. data/lib/skyward/api/cli/app_file.rb +38 -0
  10. data/lib/skyward/api/cli/check.rb +145 -0
  11. data/lib/skyward/api/cli/executable.rb +15 -0
  12. data/lib/skyward/api/cli/routes.rb +30 -0
  13. data/lib/skyward/api/cli/serve/reloader.rb +77 -0
  14. data/lib/skyward/api/cli/serve.rb +137 -0
  15. data/lib/skyward/api/cli/serve.ru +16 -0
  16. data/lib/skyward/api/cli.rb +4 -0
  17. data/lib/skyward/api/commands.rb +38 -0
  18. data/lib/skyward/api/endpoints/declarations.rb +124 -0
  19. data/lib/skyward/api/endpoints/helpers.rb +49 -0
  20. data/lib/skyward/api/endpoints/route.rb +13 -0
  21. data/lib/skyward/api/endpoints.rb +4 -0
  22. data/lib/skyward/api/inputs/coercer.rb +425 -0
  23. data/lib/skyward/api/inputs.rb +164 -0
  24. data/lib/skyward/api/middleware/line_logger.rb +20 -0
  25. data/lib/skyward/api/middleware/request_id.rb +26 -0
  26. data/lib/skyward/api/middleware/request_log.rb +46 -0
  27. data/lib/skyward/api/middleware/rescue.rb +81 -0
  28. data/lib/skyward/api/middleware.rb +4 -0
  29. data/lib/skyward/api/openapi/docs.rb +39 -0
  30. data/lib/skyward/api/openapi.rb +393 -0
  31. data/lib/skyward/api/request.rb +127 -0
  32. data/lib/skyward/api/responses/bad_request.rb +18 -0
  33. data/lib/skyward/api/responses/conflict.rb +18 -0
  34. data/lib/skyward/api/responses/created.rb +19 -0
  35. data/lib/skyward/api/responses/forbidden.rb +18 -0
  36. data/lib/skyward/api/responses/no_content.rb +13 -0
  37. data/lib/skyward/api/responses/not_found.rb +18 -0
  38. data/lib/skyward/api/responses/redirect.rb +25 -0
  39. data/lib/skyward/api/responses/unauthorized.rb +18 -0
  40. data/lib/skyward/api/responses/unprocessable.rb +18 -0
  41. data/lib/skyward/api/responses.rb +4 -0
  42. data/lib/skyward/api/return_type_error.rb +4 -0
  43. data/lib/skyward/api/routing/percent_encoding.rb +15 -0
  44. data/lib/skyward/api/routing/router.rb +115 -0
  45. data/lib/skyward/api/routing.rb +4 -0
  46. data/lib/skyward/api/serializer/writers.rb +230 -0
  47. data/lib/skyward/api/serializer.rb +139 -0
  48. data/lib/skyward/api/test/client.rb +160 -0
  49. data/lib/skyward/api/test.rb +8 -0
  50. data/lib/skyward/api/version.rb +5 -1
  51. data/lib/skyward/api.rb +118 -1
  52. data/sig/generated/skyward/api/assembly/application.rbs +22 -0
  53. data/sig/generated/skyward/api/assembly/boot.rbs +217 -0
  54. data/sig/generated/skyward/api/assembly/builder.rbs +77 -0
  55. data/sig/generated/skyward/api/assembly/dispatcher.rbs +84 -0
  56. data/sig/generated/skyward/api/assembly/static.rbs +47 -0
  57. data/sig/generated/skyward/api/assembly.rbs +4 -0
  58. data/sig/generated/skyward/api/cli/app_file.rbs +15 -0
  59. data/sig/generated/skyward/api/cli/check.rbs +76 -0
  60. data/sig/generated/skyward/api/cli/executable.rbs +11 -0
  61. data/sig/generated/skyward/api/cli/routes.rbs +19 -0
  62. data/sig/generated/skyward/api/cli/serve/reloader.rbs +46 -0
  63. data/sig/generated/skyward/api/cli/serve.rbs +56 -0
  64. data/sig/generated/skyward/api/cli.rbs +4 -0
  65. data/sig/generated/skyward/api/commands.rbs +2 -0
  66. data/sig/generated/skyward/api/endpoints/declarations.rbs +81 -0
  67. data/sig/generated/skyward/api/endpoints/helpers.rbs +49 -0
  68. data/sig/generated/skyward/api/endpoints/route.rbs +24 -0
  69. data/sig/generated/skyward/api/endpoints.rbs +4 -0
  70. data/sig/generated/skyward/api/inputs/coercer.rbs +231 -0
  71. data/sig/generated/skyward/api/inputs.rbs +75 -0
  72. data/sig/generated/skyward/api/middleware/line_logger.rbs +13 -0
  73. data/sig/generated/skyward/api/middleware/request_id.rbs +17 -0
  74. data/sig/generated/skyward/api/middleware/request_log.rbs +18 -0
  75. data/sig/generated/skyward/api/middleware/rescue.rbs +41 -0
  76. data/sig/generated/skyward/api/middleware.rbs +4 -0
  77. data/sig/generated/skyward/api/openapi/docs.rbs +17 -0
  78. data/sig/generated/skyward/api/openapi.rbs +198 -0
  79. data/sig/generated/skyward/api/request.rbs +65 -0
  80. data/sig/generated/skyward/api/responses/bad_request.rbs +14 -0
  81. data/sig/generated/skyward/api/responses/conflict.rbs +14 -0
  82. data/sig/generated/skyward/api/responses/created.rbs +15 -0
  83. data/sig/generated/skyward/api/responses/forbidden.rbs +14 -0
  84. data/sig/generated/skyward/api/responses/no_content.rbs +10 -0
  85. data/sig/generated/skyward/api/responses/not_found.rbs +14 -0
  86. data/sig/generated/skyward/api/responses/redirect.rbs +20 -0
  87. data/sig/generated/skyward/api/responses/unauthorized.rbs +14 -0
  88. data/sig/generated/skyward/api/responses/unprocessable.rbs +14 -0
  89. data/sig/generated/skyward/api/responses.rbs +4 -0
  90. data/sig/generated/skyward/api/return_type_error.rbs +4 -0
  91. data/sig/generated/skyward/api/routing/percent_encoding.rbs +11 -0
  92. data/sig/generated/skyward/api/routing/router.rbs +158 -0
  93. data/sig/generated/skyward/api/routing.rbs +4 -0
  94. data/sig/generated/skyward/api/serializer/writers.rbs +126 -0
  95. data/sig/generated/skyward/api/serializer.rbs +79 -0
  96. data/sig/generated/skyward/api/test/client.rbs +117 -0
  97. data/sig/generated/skyward/api/test.rbs +6 -0
  98. data/sig/generated/skyward/api.rbs +38 -0
  99. data/sig/manual/skyward/api/assembly/boot.rbs +3 -0
  100. data/sig/manual/skyward/api/cli/app_file.rbs +3 -0
  101. data/sig/manual/skyward/api/cli/check.rbs +3 -0
  102. data/sig/manual/skyward/api/cli/executable.rbs +3 -0
  103. data/sig/manual/skyward/api/cli/routes.rbs +3 -0
  104. data/sig/manual/skyward/api/cli/serve.rbs +3 -0
  105. data/sig/manual/skyward/api/inputs/coercer.rbs +3 -0
  106. data/sig/manual/skyward/api/openapi/docs.rbs +3 -0
  107. data/sig/manual/skyward/api/openapi.rbs +3 -0
  108. data/sig/manual/skyward/api/routing/percent_encoding.rbs +3 -0
  109. data/sig/manual/skyward/api/serializer/writers.rbs +3 -0
  110. data/sig/manual/skyward/api/test.rbs +3 -0
  111. data/sig/manual/skyward/api.rbs +21 -0
  112. data/sig/manual/zeitwerk/loader.rbs +6 -0
  113. metadata +110 -3
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ # skyward serve's composition root. Rack is reached for only here: Skyward API
4
+ # doesn't depend on it, and Falcon brings it.
5
+ require "skyward/api"
6
+
7
+ run Skyward::API::CLI::Serve.reloader(
8
+ Dir.pwd,
9
+ build: ->(config) { Rack::Builder.parse_file(config) },
10
+ clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) },
11
+ apis: -> { ObjectSpace.each_object(Skyward::API.singleton_class).to_a },
12
+ features: $LOADED_FEATURES,
13
+ # Zeitwerk has no public list of its loaders, and ObjectSpace would go on
14
+ # finding the ones serve unregisters until they're garbage collected.
15
+ loaders: -> { Zeitwerk::Registry.loaders.enum_for(:each).to_a }
16
+ )
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Skyward::API::CLI
4
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "skyward/api"
5
+
6
+ Skyward::Core::CLI.register("serve", "Serve config.ru with Falcon in development, on PORT (default 9292)") do |_args|
7
+ Skyward::API::CLI::Serve.run(
8
+ Dir.pwd,
9
+ env: ENV.to_h,
10
+ falcon: Skyward::API::CLI::Executable.find("falcon"),
11
+ kernel: Kernel
12
+ )
13
+ end
14
+
15
+ Skyward::Core::CLI.register("check", "Check signatures, boot app.rb in strict mode and run Steep") do |_args|
16
+ # So CI shows each check as it finishes, not all of them at exit.
17
+ $stdout.sync = true
18
+ exit Skyward::API::CLI::Check.run(
19
+ Dir.pwd,
20
+ out: $stdout,
21
+ capture: lambda do |env, command, chdir|
22
+ # RBS doesn't list the [:child, :out] spelling of this redirect.
23
+ output = IO.popen(env, command, chdir:, err: [:child, 1], &:read)
24
+ # RBS doesn't declare Process.last_status, set by the popen above.
25
+ [output, Process.last_status.success?] # steep:ignore NoMethod
26
+ end,
27
+ rbs_inline: Skyward::API::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
28
+ steep: Skyward::API::CLI::Executable.find("steep")
29
+ )
30
+ end
31
+
32
+ Skyward::Core::CLI.register("routes", "Print every route with its handler and signature") do |_args|
33
+ Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel) { |app| Skyward::API::CLI::Routes.table(app.endpoints) }
34
+ end
35
+
36
+ Skyward::Core::CLI.register("openapi", "Write the OpenAPI document to stdout") do |_args|
37
+ Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel) { |app| "#{JSON.pretty_generate(app.openapi)}\n" }
38
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @rbs module-self Class
4
+ module Skyward::API::Endpoints::Declarations
5
+ PARAMETER_NAME = /\A[a-z_]\w*\z/ #: Regexp
6
+
7
+ # @rbs @routes: Array[Skyward::API::Endpoints::Route]?
8
+ # @rbs @class_description: String?
9
+
10
+ # A class that hasn't declared a route, or whose routes were cleared, has its
11
+ # parent's, so a reopened subclass declares its own after them again.
12
+ # @rbs return: Array[Skyward::API::Endpoints::Route]
13
+ def routes = @routes || inherited_routes
14
+
15
+ # @rbs return: String?
16
+ def class_description = @class_description
17
+
18
+ # @rbs text: String
19
+ # @rbs return: void
20
+ def description(text)
21
+ raise ArgumentError, "#{self} already has a description" if @class_description
22
+
23
+ @class_description = text.dup.freeze
24
+ end
25
+
26
+ # skyward serve's reloading runs a reopened class's declarations again, on
27
+ # the same class, so it clears them first.
28
+ # @rbs return: void
29
+ def clear_declarations
30
+ @routes = nil
31
+ @class_description = nil
32
+ end
33
+
34
+ # @rbs path: String
35
+ # @rbs to: Symbol
36
+ # @rbs summary: String?
37
+ # @rbs description: String?
38
+ # @rbs return: void
39
+ def get(path, to:, summary: nil, description: nil)
40
+ declare(:get, path, to, summary, description)
41
+ end
42
+
43
+ # @rbs path: String
44
+ # @rbs to: Symbol
45
+ # @rbs summary: String?
46
+ # @rbs description: String?
47
+ # @rbs return: void
48
+ def post(path, to:, summary: nil, description: nil)
49
+ declare(:post, path, to, summary, description)
50
+ end
51
+
52
+ # @rbs path: String
53
+ # @rbs to: Symbol
54
+ # @rbs summary: String?
55
+ # @rbs description: String?
56
+ # @rbs return: void
57
+ def put(path, to:, summary: nil, description: nil)
58
+ declare(:put, path, to, summary, description)
59
+ end
60
+
61
+ # @rbs path: String
62
+ # @rbs to: Symbol
63
+ # @rbs summary: String?
64
+ # @rbs description: String?
65
+ # @rbs return: void
66
+ def patch(path, to:, summary: nil, description: nil)
67
+ declare(:patch, path, to, summary, description)
68
+ end
69
+
70
+ # @rbs path: String
71
+ # @rbs to: Symbol
72
+ # @rbs summary: String?
73
+ # @rbs description: String?
74
+ # @rbs return: void
75
+ def delete(path, to:, summary: nil, description: nil)
76
+ declare(:delete, path, to, summary, description)
77
+ end
78
+
79
+ private
80
+
81
+ # @rbs return: Array[Skyward::API::Endpoints::Route]
82
+ def inherited_routes
83
+ parent = superclass
84
+ # Steep types a superclass as a plain Class, but an API class's superclass extends Declarations too.
85
+ parent.is_a?(Skyward::API::Endpoints::Declarations) ? parent.routes : [] # steep:ignore UnreachableBranch
86
+ end
87
+
88
+ # @rbs verb: Symbol
89
+ # @rbs path: String
90
+ # @rbs to: Symbol
91
+ # @rbs summary: String?
92
+ # @rbs description: String?
93
+ # @rbs return: void
94
+ def declare(verb, path, to, summary, description)
95
+ problem = problem_with(path, to)
96
+ raise ArgumentError, "#{self} #{verb.upcase} #{path.inspect}: #{problem}" if problem
97
+
98
+ route = Skyward::API::Endpoints::Route.new(
99
+ verb:,
100
+ path: path.dup.freeze,
101
+ to:,
102
+ summary: summary.dup.freeze,
103
+ description: description.dup.freeze
104
+ )
105
+ @routes = [*routes, route].freeze
106
+ end
107
+
108
+ # Untyped: a caller that Steep doesn't check can pass anything.
109
+ # @rbs path: untyped
110
+ # @rbs to: untyped
111
+ # @rbs return: String?
112
+ def problem_with(path, to)
113
+ return "the path must be a String that starts with /" unless path.is_a?(String) && path.start_with?("/")
114
+
115
+ names = path.split("/").filter_map { |segment| segment.delete_prefix(":") if segment.start_with?(":") }
116
+ invalid = names.find { |name| !PARAMETER_NAME.match?(name) }
117
+ return "path parameter #{invalid.inspect} isn't a valid keyword name" if invalid
118
+
119
+ repeated = names.find { |name| names.count(name) > 1 }
120
+ return "path parameter #{repeated.inspect} is used more than once" if repeated
121
+
122
+ "to: must be a Symbol, got #{to.inspect}" unless to.is_a?(Symbol)
123
+ end
124
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Private, so a route can't name a helper as its method.
4
+ module Skyward::API::Endpoints::Helpers
5
+ private
6
+
7
+ # @rbs [T] (T value, ?headers: Hash[String, String]) -> Skyward::API::Responses::Created[T]
8
+ def created(value, headers: {}) = Skyward::API::Responses::Created.new(value:, headers:)
9
+
10
+ # @rbs headers: Hash[String, String]
11
+ # @rbs return: Skyward::API::Responses::NoContent
12
+ def no_content(headers: {}) = Skyward::API::Responses::NoContent.new(headers:)
13
+
14
+ # @rbs detail: String
15
+ # @rbs headers: Hash[String, String]
16
+ # @rbs return: Skyward::API::Responses::BadRequest
17
+ def bad_request(detail, headers: {}) = Skyward.bad_request(detail, headers:)
18
+
19
+ # @rbs detail: String
20
+ # @rbs headers: Hash[String, String]
21
+ # @rbs return: Skyward::API::Responses::Unauthorized
22
+ def unauthorized(detail, headers: {}) = Skyward.unauthorized(detail, headers:)
23
+
24
+ # @rbs detail: String
25
+ # @rbs headers: Hash[String, String]
26
+ # @rbs return: Skyward::API::Responses::Forbidden
27
+ def forbidden(detail, headers: {}) = Skyward.forbidden(detail, headers:)
28
+
29
+ # @rbs detail: String?
30
+ # @rbs headers: Hash[String, String]
31
+ # @rbs return: Skyward::API::Responses::NotFound
32
+ def not_found(detail = nil, headers: {}) = Skyward::API::Responses::NotFound.new(detail:, headers:)
33
+
34
+ # @rbs detail: String
35
+ # @rbs headers: Hash[String, String]
36
+ # @rbs return: Skyward::API::Responses::Conflict
37
+ def conflict(detail, headers: {}) = Skyward::API::Responses::Conflict.new(detail:, headers:)
38
+
39
+ # @rbs detail: String
40
+ # @rbs headers: Hash[String, String]
41
+ # @rbs return: Skyward::API::Responses::Unprocessable
42
+ def unprocessable(detail, headers: {}) = Skyward::API::Responses::Unprocessable.new(detail:, headers:)
43
+
44
+ # @rbs to: String
45
+ # @rbs status: Integer
46
+ # @rbs headers: Hash[String, String]
47
+ # @rbs return: Skyward::API::Responses::Redirect
48
+ def redirect(to, status: 303, headers: {}) = Skyward.redirect(to, status:, headers:)
49
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rbs-inline only types a Data.define assigned to a bare constant name, so
4
+ # Route is assigned inside the module rather than as Skyward::API::Endpoints::Route.
5
+ module Skyward::API::Endpoints
6
+ Route = Data.define(
7
+ :verb, #: Symbol
8
+ :path, #: String
9
+ :to, #: Symbol
10
+ :summary, #: String?
11
+ :description #: String?
12
+ )
13
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Skyward::API::Endpoints
4
+ end
@@ -0,0 +1,425 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "json"
5
+
6
+ module Skyward::API::Inputs::Coercer
7
+ extend self
8
+
9
+ # @rbs!
10
+ # type result = Ok | Invalid
11
+ # type t = ^(untyped raw, String at) -> result
12
+ # type seen = Hash[[Integer, Integer], result]
13
+ # type coercer = ^(untyped raw, String at, seen seen) -> result
14
+
15
+ Error = Data.define(
16
+ :at, #: String
17
+ :message #: String
18
+ )
19
+
20
+ Ok = Data.define(
21
+ :value #: untyped
22
+ )
23
+
24
+ Invalid = Data.define(
25
+ :errors #: Array[Error]
26
+ )
27
+
28
+ # Coercion stops once it has found this many problems, so a small body can't
29
+ # produce a large response.
30
+ MAX_ERRORS = 1_000 #: Integer
31
+
32
+ # A message's expected type and a hash's key in a path are cut to this many
33
+ # characters, so a large written type or key can't make a 422 many times
34
+ # larger than the body that caused it.
35
+ MAX_SHOWN = 200 #: Integer
36
+
37
+ # Stands for every problem a union's member finds, since the union reports
38
+ # none of them.
39
+ MISFIT = Invalid.new(errors: [Error.new(at: "", message: "doesn't fit")]) #: Invalid
40
+
41
+ # INTEGER, DATE and TIME match a String's bytes, because a path parameter
42
+ # can be any bytes, and Regexp#match raises on a String that isn't UTF-8.
43
+ INTEGER = /\A-?\d+\z/ #: Regexp
44
+
45
+ BOOLEANS = { "true" => true, "false" => false, "1" => true, "0" => false }.freeze #: Hash[String, bool]
46
+
47
+ DATE = /\A(\d{4})-(\d{2})-(\d{2})\z/ #: Regexp
48
+
49
+ # The fraction is cut to nanoseconds, which bounds what converting it costs.
50
+ TIME = /
51
+ \A(\d{4}-\d{2}-\d{2})
52
+ T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(?:\.(\d{1,9})\d*+)?
53
+ (Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)\z
54
+ /x #: Regexp
55
+
56
+ NAMES = {
57
+ integer: "Integer",
58
+ float: "Float",
59
+ string: "String",
60
+ bool: "bool",
61
+ date: "Date",
62
+ time: "Time",
63
+ untyped: "untyped"
64
+ }.freeze #: Hash[Skyward::Core::Types::scalar, String]
65
+
66
+ FORMATS = { date: "Date (YYYY-MM-DD)", time: "Time (ISO 8601)" }.freeze #: Hash[Skyward::Core::Types::scalar, String]
67
+
68
+ # Path and query values are Strings, so with strings: true a coercer parses them.
69
+ # @rbs type: Skyward::Core::Types::t
70
+ # @rbs strings: bool
71
+ # @rbs return: t
72
+ def compile(type, strings:)
73
+ coercer = build(type, strings, false, {})
74
+ ->(raw, at) { coercer.call(raw, at, {}) }
75
+ end
76
+
77
+ # @rbs type: Skyward::Core::Types::t
78
+ # @rbs required: bool
79
+ # @rbs at: String
80
+ # @rbs return: result?
81
+ def absent(type, required, at)
82
+ return unless required
83
+ return Ok.new(value: nil) if type.is_a?(Skyward::Core::Types::Nullable)
84
+
85
+ Invalid.new(errors: [Error.new(at:, message: "is required")])
86
+ end
87
+
88
+ # @rbs results: Hash[Symbol, result]
89
+ # @rbs return: result
90
+ def combine(results)
91
+ errors = errors(results.values)
92
+ return Invalid.new(errors:) unless errors.empty?
93
+
94
+ ok = results #: Hash[Symbol, Ok]
95
+ Ok.new(value: ok.transform_values(&:value))
96
+ end
97
+
98
+ private
99
+
100
+ # A union reports its own mismatch, so with member: true a coercer stops at
101
+ # its first problem and never writes a message.
102
+ # @rbs type: Skyward::Core::Types::t
103
+ # @rbs strings: bool
104
+ # @rbs member: bool
105
+ # @rbs unions: Hash[[Skyward::Core::Types::Union, bool], coercer]
106
+ # @rbs return: coercer
107
+ def build(type, strings, member, unions)
108
+ expected = expectation(type) unless member
109
+ limit = member ? 1 : MAX_ERRORS
110
+ case type
111
+ when Skyward::Core::Types::Scalar then scalar(parser(type.name, strings), expected)
112
+ when Skyward::Core::Types::Literal then literal(type.value, strings, expected)
113
+ when Skyward::Core::Types::Enum then enum(type.symbols, expected)
114
+ when Skyward::Core::Types::Nullable then nullable(build(type.type, strings, member, unions))
115
+ when Skyward::Core::Types::ArrayOf then array(build(type.type, strings, member, unions), strings, limit, expected)
116
+ when Skyward::Core::Types::HashOf then hash_of(build(type.type, strings, member, unions), limit, expected)
117
+ when Skyward::Core::Types::Record then object(fields(type, strings, member, unions), limit, expected, &:itself)
118
+ when Skyward::Core::Types::Named
119
+ klass = type.klass
120
+ object(fields(type, strings, member, unions), limit, expected) { |values| klass.new(**values) }
121
+ # Equal unions share one coercer, which is what lets one remember its results.
122
+ else unions[[type, member]] ||= union(type.types.map { |one| build(one, strings, true, unions) }, member, expected)
123
+ end
124
+ end
125
+
126
+ # @rbs type: Skyward::Core::Types::Record | Skyward::Core::Types::Named
127
+ # @rbs strings: bool
128
+ # @rbs member: bool
129
+ # @rbs unions: Hash[[Skyward::Core::Types::Union, bool], coercer]
130
+ # @rbs return: Array[[Skyward::Core::Types::Field, coercer]]
131
+ def fields(type, strings, member, unions)
132
+ type.fields.map { |field| [field, build(field.type, strings, member, unions)] }
133
+ end
134
+
135
+ # @rbs parse: ^(untyped) -> Ok?
136
+ # @rbs expected: String?
137
+ # @rbs return: coercer
138
+ def scalar(parse, expected) = ->(raw, at, _seen) { parse.call(raw) || mismatch(expected, raw, at) }
139
+
140
+ # @rbs name: Skyward::Core::Types::scalar
141
+ # @rbs strings: bool
142
+ # @rbs return: ^(untyped) -> Ok?
143
+ def parser(name, strings)
144
+ case name
145
+ when :integer then ->(raw) { integer(raw, strings) }
146
+ when :float then ->(raw) { float(raw, strings) }
147
+ when :bool then ->(raw) { bool(raw, strings) }
148
+ when :string then ->(raw) { Ok.new(value: raw) if raw.is_a?(String) }
149
+ when :date then ->(raw) { date(raw) }
150
+ when :time then ->(raw) { time(raw) }
151
+ else ->(raw) { Ok.new(value: strings ? last(raw) : symbolized(raw)) }
152
+ end
153
+ end
154
+
155
+ # A query key given more than once arrives as an Array of its values, of
156
+ # which untyped takes the last, as Rack's params do.
157
+ # @rbs raw: String | Array[String]
158
+ # @rbs return: String?
159
+ def last(raw) = raw.is_a?(Array) ? raw.last : raw
160
+
161
+ # @rbs raw: untyped
162
+ # @rbs return: untyped
163
+ def symbolized(raw)
164
+ case raw
165
+ when Hash then raw.to_h { |key, value| [key.to_sym, symbolized(value)] }
166
+ when Array then raw.map { |item| symbolized(item) }
167
+ else raw
168
+ end
169
+ end
170
+
171
+ # @rbs raw: untyped
172
+ # @rbs strings: bool
173
+ # @rbs return: Ok?
174
+ def integer(raw, strings)
175
+ case raw
176
+ when Integer then Ok.new(value: raw)
177
+ when String then Ok.new(value: raw.to_i) if strings && INTEGER.match?(raw.b)
178
+ end
179
+ end
180
+
181
+ # @rbs raw: untyped
182
+ # @rbs strings: bool
183
+ # @rbs return: Ok?
184
+ def float(raw, strings)
185
+ number =
186
+ case raw
187
+ when Integer, Float then raw.to_f
188
+ when String then Float(raw, exception: false) if strings
189
+ end
190
+ Ok.new(value: number) if number&.finite?
191
+ end
192
+
193
+ # @rbs raw: untyped
194
+ # @rbs strings: bool
195
+ # @rbs return: Ok?
196
+ def bool(raw, strings)
197
+ case raw
198
+ when true, false then Ok.new(value: raw)
199
+ when String then Ok.new(value: BOOLEANS.fetch(raw)) if strings && BOOLEANS.key?(raw)
200
+ end
201
+ end
202
+
203
+ # @rbs raw: untyped
204
+ # @rbs return: Ok?
205
+ def date(raw)
206
+ match = DATE.match(raw.b) if raw.is_a?(String)
207
+ return unless match
208
+
209
+ year, month, day = match.captures.map(&:to_i) #: [Integer, Integer, Integer]
210
+ Ok.new(value: Date.new(year, month, day)) if Date.valid_date?(year, month, day)
211
+ end
212
+
213
+ # @rbs raw: untyped
214
+ # @rbs return: Ok?
215
+ def time(raw)
216
+ match = TIME.match(raw.b) if raw.is_a?(String)
217
+ # Time.new rolls an impossible day, like February 30, into the next month.
218
+ day = date(match[1]) if match
219
+ return unless match && day
220
+
221
+ _, hour, minute, second, fraction, zone = match.captures
222
+ on = day.value
223
+ seconds = Rational("#{second}.#{fraction || 0}")
224
+ Ok.new(value: Time.new(on.year, on.month, on.day, hour.to_i, minute.to_i, seconds, zone))
225
+ end
226
+
227
+ # @rbs value: Skyward::Core::Types::literal
228
+ # @rbs strings: bool
229
+ # @rbs expected: String?
230
+ # @rbs return: coercer
231
+ def literal(value, strings, expected)
232
+ name =
233
+ case value
234
+ when Integer then :integer
235
+ when String then :string
236
+ when nil then :untyped
237
+ else :bool
238
+ end #: Skyward::Core::Types::scalar
239
+ parse = parser(name, strings)
240
+ lambda do |raw, at, _seen|
241
+ parsed = parse.call(raw)
242
+ parsed && parsed.value == value ? parsed : mismatch(expected, raw, at)
243
+ end
244
+ end
245
+
246
+ # @rbs symbols: Array[Symbol]
247
+ # @rbs expected: String?
248
+ # @rbs return: coercer
249
+ def enum(symbols, expected)
250
+ by_name = symbols.to_h { |symbol| [symbol.name, symbol] }
251
+ lambda do |raw, at, _seen|
252
+ symbol = by_name.fetch(raw, nil)
253
+ symbol ? Ok.new(value: symbol) : mismatch(expected, raw, at)
254
+ end
255
+ end
256
+
257
+ # @rbs coercer: coercer
258
+ # @rbs return: coercer
259
+ def nullable(coercer) = ->(raw, at, seen) { raw.nil? ? Ok.new(value: nil) : coercer.call(raw, at, seen) }
260
+
261
+ # @rbs item: coercer
262
+ # @rbs strings: bool
263
+ # @rbs limit: Integer
264
+ # @rbs expected: String?
265
+ # @rbs return: coercer
266
+ def array(item, strings, limit, expected)
267
+ lambda do |raw, at, seen|
268
+ values =
269
+ case raw
270
+ when Array then raw
271
+ # A query string repeats a key for each item, so one value is one item.
272
+ when String then [raw] if strings
273
+ end
274
+ next mismatch(expected, raw, at) unless values
275
+
276
+ collected(items(values, item, limit, seen) { |index| "#{at}[#{index}]" }, &:itself)
277
+ end
278
+ end
279
+
280
+ # @rbs value: coercer
281
+ # @rbs limit: Integer
282
+ # @rbs expected: String?
283
+ # @rbs return: coercer
284
+ def hash_of(value, limit, expected)
285
+ lambda do |raw, at, seen|
286
+ next mismatch(expected, raw, at) unless raw.is_a?(Hash)
287
+
288
+ keys = raw.keys
289
+ coerced = items(raw.values, value, limit, seen) do |index|
290
+ # JSON-quoted so a dot or a bracket in a key can't be read as part of the path.
291
+ "#{at}[#{JSON.generate(cut(keys.fetch(index)))}]"
292
+ end
293
+ collected(coerced) { |values| keys.zip(values).to_h }
294
+ end
295
+ end
296
+
297
+ # @rbs values: Array[untyped]
298
+ # @rbs item: coercer
299
+ # @rbs limit: Integer
300
+ # @rbs seen: seen
301
+ # @rbs &: (Integer) -> String
302
+ # @rbs return: Array[result]
303
+ def items(values, item, limit, seen)
304
+ none = [[], 0] #: [Array[result], Integer]
305
+ coerced = values.each_with_index.reduce(none) do |state, (value, index)|
306
+ done, count = state
307
+ break state if count >= limit
308
+
309
+ result = item.call(value, yield(index), seen)
310
+ # Appended in place: copying the array for each item would be quadratic.
311
+ [done << result, count + errors([result]).size]
312
+ end
313
+ coerced.first
314
+ end
315
+
316
+ # @rbs results: Array[result]
317
+ # @rbs &: (Array[untyped]) -> untyped
318
+ # @rbs return: result
319
+ def collected(results)
320
+ errors = errors(results)
321
+ return Invalid.new(errors:) unless errors.empty?
322
+
323
+ ok = results #: Array[Ok]
324
+ Ok.new(value: yield(ok.map(&:value)))
325
+ end
326
+
327
+ # @rbs fields: Array[[Skyward::Core::Types::Field, coercer]]
328
+ # @rbs limit: Integer
329
+ # @rbs expected: String?
330
+ # @rbs &: (Hash[Symbol, untyped]) -> untyped
331
+ # @rbs return: coercer
332
+ def object(fields, limit, expected, &)
333
+ lambda do |raw, at, seen|
334
+ next mismatch(expected, raw, at) unless raw.is_a?(Hash)
335
+
336
+ none = [[], 0] #: [Array[[Symbol, result]], Integer]
337
+ coerced = fields.reduce(none) do |state, (field, coercer)|
338
+ done, count = state
339
+ break state if count >= limit
340
+
341
+ name = field.name.to_s
342
+ found = "#{at}.#{name}"
343
+ result =
344
+ raw.key?(name) ? coercer.call(raw.fetch(name), found, seen) : absent(field.type, field.required, found)
345
+ case result
346
+ when Ok then [done << [field.name, result], count]
347
+ when Invalid then [done << [field.name, result], count + result.errors.size]
348
+ else state
349
+ end
350
+ end
351
+ combined = combine(coerced.first.to_h)
352
+ combined.is_a?(Ok) ? Ok.new(value: yield(combined.value)) : combined
353
+ end
354
+ end
355
+
356
+ # @rbs coercers: Array[coercer]
357
+ # @rbs member: bool
358
+ # @rbs expected: String?
359
+ # @rbs return: coercer
360
+ def union(coercers, member, expected)
361
+ fit = lambda do |raw, at, seen|
362
+ coercers.lazy.map { |coercer| coercer.call(raw, at, seen) }.find { |result| result.is_a?(Ok) } ||
363
+ mismatch(expected, raw, at)
364
+ end
365
+ return fit unless member
366
+
367
+ # Overlapping members, such as two records with the same field, each coerce
368
+ # the same value as the same nested union, which costs 2^depth unless the
369
+ # first result is kept. A member's result doesn't depend on where it is.
370
+ ->(raw, at, seen) { seen[[fit.__id__, raw.__id__]] ||= fit.call(raw, at, seen) }
371
+ end
372
+
373
+ # @rbs results: Array[result]
374
+ # @rbs return: Array[Error]
375
+ def errors(results) = results.flat_map { |result| result.is_a?(Invalid) ? result.errors : [] }
376
+
377
+ # @rbs type: Skyward::Core::Types::t
378
+ # @rbs return: String
379
+ def expectation(type)
380
+ cut(type.is_a?(Skyward::Core::Types::Scalar) ? FORMATS.fetch(type.name) { written(type) } : written(type))
381
+ end
382
+
383
+ # @rbs text: String
384
+ # @rbs return: String
385
+ def cut(text) = text.length > MAX_SHOWN ? "#{text[0, MAX_SHOWN - 1]}…" : text
386
+
387
+ # @rbs expected: String?
388
+ # @rbs raw: untyped
389
+ # @rbs at: String
390
+ # @rbs return: Invalid
391
+ def mismatch(expected, raw, at)
392
+ return MISFIT unless expected
393
+
394
+ # A path parameter can be any bytes, and a body any number, nested as deep
395
+ # as JSON.parse allows, all of which JSON.generate refuses by default.
396
+ got = JSON.generate(raw.is_a?(String) ? raw.scrub : raw, allow_nan: true, max_nesting: false)
397
+ Invalid.new(errors: [Error.new(at:, message: "expected #{expected}, got #{got}")])
398
+ end
399
+
400
+ # @rbs type: Skyward::Core::Types::t
401
+ # @rbs return: String
402
+ def written(type)
403
+ case type
404
+ when Skyward::Core::Types::Scalar then NAMES.fetch(type.name)
405
+ when Skyward::Core::Types::Literal then type.value.inspect
406
+ when Skyward::Core::Types::Enum then type.symbols.map(&:inspect).join(" | ")
407
+ when Skyward::Core::Types::Nullable then nullable_written(type.type)
408
+ when Skyward::Core::Types::ArrayOf then "Array[#{written(type.type)}]"
409
+ when Skyward::Core::Types::HashOf then "Hash[String, #{written(type.type)}]"
410
+ when Skyward::Core::Types::Record
411
+ fields = type.fields.map { |field| "#{"?" unless field.required}#{field.name}: #{written(field.type)}" }
412
+ "{ #{fields.join(", ")} }"
413
+ when Skyward::Core::Types::Named then type.name
414
+ else type.types.map { |member| written(member) }.join(" | ")
415
+ end
416
+ end
417
+
418
+ # @rbs type: Skyward::Core::Types::t
419
+ # @rbs return: String
420
+ def nullable_written(type)
421
+ plural = type.is_a?(Skyward::Core::Types::Union) ||
422
+ (type.is_a?(Skyward::Core::Types::Enum) && type.symbols.size > 1)
423
+ plural ? "(#{written(type)})?" : "#{written(type)}?"
424
+ end
425
+ end