lingara-apps 0.1.0.pre.alpha.3

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,239 @@
1
+ =begin
2
+ #Lingara apps
3
+
4
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
5
+
6
+ The version of the OpenAPI document: 2026-10-affable-towhee
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ Generator version: 7.14.0
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'time'
15
+
16
+ module Lingara::Apps
17
+ class Card
18
+ attr_accessor :elements
19
+
20
+ # Attribute mapping from ruby-style variable name to JSON key.
21
+ def self.attribute_map
22
+ {
23
+ :'elements' => :'elements'
24
+ }
25
+ end
26
+
27
+ # Returns attribute mapping this model knows about
28
+ def self.acceptable_attribute_map
29
+ attribute_map
30
+ end
31
+
32
+ # Returns all the JSON keys this model knows about
33
+ def self.acceptable_attributes
34
+ acceptable_attribute_map.values
35
+ end
36
+
37
+ # Attribute type mapping.
38
+ def self.openapi_types
39
+ {
40
+ :'elements' => :'Array<Object>'
41
+ }
42
+ end
43
+
44
+ # List of attributes with nullable: true
45
+ def self.openapi_nullable
46
+ Set.new([
47
+ ])
48
+ end
49
+
50
+ # Initializes the object
51
+ # @param [Hash] attributes Model attributes in the form of hash
52
+ def initialize(attributes = {})
53
+ if (!attributes.is_a?(Hash))
54
+ fail ArgumentError, "The input argument (attributes) must be a hash in `Lingara::Apps::Card` initialize method"
55
+ end
56
+
57
+ # check to see if the attribute exists and convert string to symbol for hash key
58
+ acceptable_attribute_map = self.class.acceptable_attribute_map
59
+ attributes = attributes.each_with_object({}) { |(k, v), h|
60
+ if (!acceptable_attribute_map.key?(k.to_sym))
61
+ fail ArgumentError, "`#{k}` is not a valid attribute in `Lingara::Apps::Card`. Please check the name to make sure it's valid. List of attributes: " + acceptable_attribute_map.keys.inspect
62
+ end
63
+ h[k.to_sym] = v
64
+ }
65
+
66
+ if attributes.key?(:'elements')
67
+ if (value = attributes[:'elements']).is_a?(Array)
68
+ self.elements = value
69
+ end
70
+ else
71
+ self.elements = nil
72
+ end
73
+ end
74
+
75
+ # Show invalid properties with the reasons. Usually used together with valid?
76
+ # @return Array for valid properties with the reasons
77
+ def list_invalid_properties
78
+ warn '[DEPRECATED] the `list_invalid_properties` method is obsolete'
79
+ invalid_properties = Array.new
80
+ if @elements.nil?
81
+ invalid_properties.push('invalid value for "elements", elements cannot be nil.')
82
+ end
83
+
84
+ invalid_properties
85
+ end
86
+
87
+ # Check to see if the all the properties in the model are valid
88
+ # @return true if the model is valid
89
+ def valid?
90
+ warn '[DEPRECATED] the `valid?` method is obsolete'
91
+ return false if @elements.nil?
92
+ true
93
+ end
94
+
95
+ # Custom attribute writer method with validation
96
+ # @param [Object] elements Value to be assigned
97
+ def elements=(elements)
98
+ if elements.nil?
99
+ fail ArgumentError, 'elements cannot be nil'
100
+ end
101
+
102
+ @elements = elements
103
+ end
104
+
105
+ # Checks equality by comparing each attribute.
106
+ # @param [Object] Object to be compared
107
+ def ==(o)
108
+ return true if self.equal?(o)
109
+ self.class == o.class &&
110
+ elements == o.elements
111
+ end
112
+
113
+ # @see the `==` method
114
+ # @param [Object] Object to be compared
115
+ def eql?(o)
116
+ self == o
117
+ end
118
+
119
+ # Calculates hash code according to all attributes.
120
+ # @return [Integer] Hash code
121
+ def hash
122
+ [elements].hash
123
+ end
124
+
125
+ # Builds the object from hash
126
+ # @param [Hash] attributes Model attributes in the form of hash
127
+ # @return [Object] Returns the model itself
128
+ def self.build_from_hash(attributes)
129
+ return nil unless attributes.is_a?(Hash)
130
+ attributes = attributes.transform_keys(&:to_sym)
131
+ transformed_hash = {}
132
+ openapi_types.each_pair do |key, type|
133
+ if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil?
134
+ transformed_hash["#{key}"] = nil
135
+ elsif type =~ /\AArray<(.*)>/i
136
+ # check to ensure the input is an array given that the attribute
137
+ # is documented as an array but the input is not
138
+ if attributes[attribute_map[key]].is_a?(Array)
139
+ transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) }
140
+ end
141
+ elsif !attributes[attribute_map[key]].nil?
142
+ transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]])
143
+ end
144
+ end
145
+ new(transformed_hash)
146
+ end
147
+
148
+ # Deserializes the data based on type
149
+ # @param string type Data type
150
+ # @param string value Value to be deserialized
151
+ # @return [Object] Deserialized data
152
+ def self._deserialize(type, value)
153
+ case type.to_sym
154
+ when :Time
155
+ Time.parse(value)
156
+ when :Date
157
+ Date.parse(value)
158
+ when :String
159
+ value.to_s
160
+ when :Integer
161
+ value.to_i
162
+ when :Float
163
+ value.to_f
164
+ when :Boolean
165
+ if value.to_s =~ /\A(true|t|yes|y|1)\z/i
166
+ true
167
+ else
168
+ false
169
+ end
170
+ when :Object
171
+ # generic object (usually a Hash), return directly
172
+ value
173
+ when /\AArray<(?<inner_type>.+)>\z/
174
+ inner_type = Regexp.last_match[:inner_type]
175
+ value.map { |v| _deserialize(inner_type, v) }
176
+ when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
177
+ k_type = Regexp.last_match[:k_type]
178
+ v_type = Regexp.last_match[:v_type]
179
+ {}.tap do |hash|
180
+ value.each do |k, v|
181
+ hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
182
+ end
183
+ end
184
+ else # model
185
+ # models (e.g. Pet) or oneOf
186
+ klass = Lingara::Apps.const_get(type)
187
+ klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
188
+ end
189
+ end
190
+
191
+ # Returns the string representation of the object
192
+ # @return [String] String presentation of the object
193
+ def to_s
194
+ to_hash.to_s
195
+ end
196
+
197
+ # to_body is an alias to to_hash (backward compatibility)
198
+ # @return [Hash] Returns the object in the form of hash
199
+ def to_body
200
+ to_hash
201
+ end
202
+
203
+ # Returns the object in the form of hash
204
+ # @return [Hash] Returns the object in the form of hash
205
+ def to_hash
206
+ hash = {}
207
+ self.class.attribute_map.each_pair do |attr, param|
208
+ value = self.send(attr)
209
+ if value.nil?
210
+ is_nullable = self.class.openapi_nullable.include?(attr)
211
+ next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
212
+ end
213
+
214
+ hash[param] = _to_hash(value)
215
+ end
216
+ hash
217
+ end
218
+
219
+ # Outputs non-array value in the form of hash
220
+ # For object, use to_hash. Otherwise, just return the value
221
+ # @param [Object] value Any valid value
222
+ # @return [Hash] Returns the value in the form of hash
223
+ def _to_hash(value)
224
+ if value.is_a?(Array)
225
+ value.compact.map { |v| _to_hash(v) }
226
+ elsif value.is_a?(Hash)
227
+ {}.tap do |hash|
228
+ value.each { |k, v| hash[k] = _to_hash(v) }
229
+ end
230
+ elsif value.respond_to? :to_hash
231
+ value.to_hash
232
+ else
233
+ value
234
+ end
235
+ end
236
+
237
+ end
238
+
239
+ end
@@ -0,0 +1,227 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Lingara
6
+ module Apps
7
+ # A card or reply the relay would clamp, refused with the first rule it
8
+ # breaks. #reason is one of Limits::REASONS.
9
+ class CardLimitError < StandardError
10
+ attr_reader :reason
11
+
12
+ def initialize(reason)
13
+ @reason = reason
14
+ super("the card breaks the #{reason} rule")
15
+ end
16
+ end
17
+
18
+ # The card rules (ADR 30.9.26am D5): the relay's clamp restated as
19
+ # refusals, held to conformance/vectors/card-limits.json and to the
20
+ # contract's reference validator. Every limit is a constant here and
21
+ # nowhere else, because the view carries none of them: they are
22
+ # post-parse clamps.
23
+ #
24
+ # A "character" is a Unicode scalar value (String#length on UTF-8), never
25
+ # a grapheme. "Empty" is empty after trimming Unicode White_Space, which
26
+ # String#strip does not do (it trims ASCII only). Patterns match the
27
+ # whole string (\A…\z), never one line of it as ^…$ would.
28
+ module Limits
29
+ # The largest reply body the relay reads, in bytes.
30
+ REPLY_MAX_BYTES = 32_768
31
+ # The largest request body a kit reads, in bytes.
32
+ REQUEST_MAX_BYTES = 65_536
33
+ MAX_ELEMENTS = 24
34
+ MAX_BUTTONS = 4
35
+ MAX_LIST_ITEMS = 20
36
+ TUTOR_NOTE_MAX_CHARS = 280
37
+ MAX_URL_BYTES = 2048
38
+
39
+ HEADING_MAX_CHARS = 80
40
+ TEXT_MAX_CHARS = 600
41
+ TERM_WORD_MAX_CHARS = 60
42
+ TERM_READING_MAX_CHARS = 120
43
+ TERM_GLOSS_MAX_CHARS = 160
44
+ PROGRESS_LABEL_MAX_CHARS = 60
45
+ BUTTON_LABEL_MAX_CHARS = 32
46
+ LINK_LABEL_MAX_CHARS = 60
47
+
48
+ LANG_PATTERN = /\A[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}\z/
49
+ ACTION_PATTERN = /\A[A-Za-z0-9_.:-]{1,64}\z/
50
+
51
+ # The refusal reasons, in the contract's order: a reply's reason is the
52
+ # first it breaks.
53
+ REASONS = %i[control_chars text_length heading_level progress_range lang link button_action buttons list_items
54
+ empty_element elements empty_card tutor_note_length reply_too_large].freeze
55
+
56
+ # C0 and C1 controls, and the bidi overrides and isolates; the second
57
+ # leaves out `\n`.
58
+ CONTROL = /[\u0000-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/
59
+ CONTROL_BUT_NEWLINE = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/
60
+ EDGES = /\A\p{White_Space}+|\p{White_Space}+\z/
61
+
62
+ # One text field's rule: its limit, whether `\n` is legal, whether it
63
+ # must be non-empty.
64
+ Field = Data.define(:limit, :newline, :required)
65
+ HEADING = Field.new(HEADING_MAX_CHARS, false, true)
66
+ TEXT = Field.new(TEXT_MAX_CHARS, true, true)
67
+ WORD = Field.new(TERM_WORD_MAX_CHARS, false, true)
68
+ READING = Field.new(TERM_READING_MAX_CHARS, false, false)
69
+ GLOSS = Field.new(TERM_GLOSS_MAX_CHARS, false, false)
70
+ PROGRESS_LABEL = Field.new(PROGRESS_LABEL_MAX_CHARS, false, true)
71
+ BUTTON_LABEL = Field.new(BUTTON_LABEL_MAX_CHARS, false, true)
72
+ LINK_LABEL = Field.new(LINK_LABEL_MAX_CHARS, false, true)
73
+ # `lang`, `button.action` and `link.url`: no length limit of their own.
74
+ RAW = Field.new(Float::INFINITY, false, false)
75
+
76
+ # The rules a reply breaks, collected; the reason is the first in
77
+ # REASONS order, as the reference validator's BTreeSet minimum is.
78
+ class Found
79
+ def initialize
80
+ @broken = []
81
+ end
82
+
83
+ def flag(reason, broken)
84
+ @broken << reason if broken
85
+ end
86
+
87
+ def raise_first
88
+ reason = REASONS.find { |r| @broken.include?(r) }
89
+ raise CardLimitError, reason if reason
90
+ end
91
+
92
+ def text(value, rule)
93
+ unless value.is_a?(String)
94
+ flag(:empty_element, rule.required)
95
+ return nil
96
+ end
97
+ flag(:control_chars, Limits.control?(value, rule.newline))
98
+ flag(:text_length, value.length > rule.limit)
99
+ flag(:empty_element, rule.required && Limits.trim(value).empty?)
100
+ value
101
+ end
102
+
103
+ def lang(value)
104
+ tag = text(value, RAW)
105
+ flag(:lang, !tag.match?(LANG_PATTERN)) if tag
106
+ end
107
+
108
+ def item(item)
109
+ case item["type"]
110
+ when "text"
111
+ text(item["text"], TEXT)
112
+ lang(item["lang"])
113
+ when "term"
114
+ text(item["word"], WORD)
115
+ text(item["reading"], READING) unless item["reading"].nil?
116
+ text(item["gloss"], GLOSS) unless item["gloss"].nil?
117
+ lang(item["lang"])
118
+ end
119
+ end
120
+
121
+ def element(e)
122
+ case e["type"]
123
+ when "heading"
124
+ text(e["text"], HEADING)
125
+ flag(:heading_level, !(e["level"].is_a?(Integer) && [1, 2].include?(e["level"])))
126
+ when "text", "term" then item(e)
127
+ when "list" then list(e)
128
+ when "progress"
129
+ flag(:progress_range, !(e["value"].is_a?(Numeric) && e["value"].between?(0, 1)))
130
+ text(e["label"], PROGRESS_LABEL)
131
+ when "button"
132
+ text(e["label"], BUTTON_LABEL)
133
+ flag(:button_action, !text(e["action"], RAW).to_s.match?(ACTION_PATTERN))
134
+ when "link"
135
+ text(e["label"], LINK_LABEL)
136
+ flag(:link, !Limits.safe_link?(text(e["url"], RAW).to_s))
137
+ end
138
+ end
139
+
140
+ def list(e)
141
+ items = e["items"].is_a?(Array) ? e["items"] : []
142
+ items.each { |i| item(i.is_a?(Hash) ? i : {}) }
143
+ flag(:list_items, items.empty? || items.size > MAX_LIST_ITEMS)
144
+ end
145
+
146
+ def card(card)
147
+ raw = card.is_a?(Hash) ? card["elements"] : nil
148
+ elements = Array(raw.is_a?(Array) ? raw : nil).map { |e| e.is_a?(Hash) ? e : {} }
149
+ elements.each { |e| element(e) }
150
+ flag(:buttons, elements.count { |e| e["type"] == "button" } > MAX_BUTTONS)
151
+ flag(:elements, elements.size > MAX_ELEMENTS)
152
+ flag(:empty_card, elements.empty?)
153
+ end
154
+
155
+ def tutor_note(note)
156
+ return unless note.is_a?(String)
157
+ flag(:control_chars, Limits.control?(note, true))
158
+ # The relay turns `\n` into a space and trims before it counts.
159
+ flag(:tutor_note_length, Limits.trim(note.tr("\n", " ")).length > TUTOR_NOTE_MAX_CHARS)
160
+ end
161
+ end
162
+
163
+ module_function
164
+
165
+ # Trims Unicode White_Space from both ends.
166
+ def trim(text)
167
+ text.gsub(EDGES, "")
168
+ end
169
+
170
+ # Whether `text` holds a refused character, `\n` aside when `newline`.
171
+ def control?(text, newline)
172
+ text.match?(newline ? CONTROL_BUT_NEWLINE : CONTROL)
173
+ end
174
+
175
+ # The relay's cut, never applied implicitly: over `limit` scalar values,
176
+ # the first `limit − 1` and `…`; otherwise unchanged.
177
+ def truncate(text, limit)
178
+ return text if text.length <= limit
179
+ "#{text[0, [limit - 1, 0].max]}…"
180
+ end
181
+
182
+ # `https`, no user information, a host name (never an IP address), at
183
+ # most MAX_URL_BYTES. Read as a WHATWG parser reads a special URL: a
184
+ # host whose last label is a number is IPv4 (127.1, 0x7f.1).
185
+ def safe_link?(raw)
186
+ return false if raw.bytesize > MAX_URL_BYTES
187
+ authority = raw[%r{\Ahttps://([^/?#\\]*)}i, 1]
188
+ return false if authority.nil? || authority.include?("@")
189
+ host, port = authority.match(/\A(.*?)(?::(\d*))?\z/m).captures
190
+ return false if port && !port.empty? && port.to_i > 65_535
191
+ !host.empty? && !host.match?(%r{[\u0000\t\n\r #/:<>?@\[\\\]^|%]}) && !ends_in_number?(host)
192
+ end
193
+
194
+ def ends_in_number?(host)
195
+ last = host.delete_suffix(".").split(".").last.to_s.downcase
196
+ return false if last.empty?
197
+ last.match?(/\A(?:\d+|0x\h*)\z/)
198
+ end
199
+
200
+ # Every card rule, the tutor note, and the size of the reply encoded
201
+ # exactly as it will be sent: compact JSON, raw UTF-8, `/` unescaped,
202
+ # an absent tutor_note omitted. Returns those bytes, or raises
203
+ # CardLimitError with the first reason. Takes the generic JSON shape
204
+ # (a Hash with String keys), so a vector feeds it as it is.
205
+ def validate_reply(reply)
206
+ found = Found.new
207
+ reply = {} unless reply.is_a?(Hash)
208
+ found.card(reply["card"])
209
+ found.tutor_note(reply["tutor_note"])
210
+ found.raise_first
211
+ bytes = JSON.generate(reply)
212
+ raise CardLimitError, :reply_too_large if bytes.bytesize > REPLY_MAX_BYTES
213
+ bytes
214
+ end
215
+
216
+ # The card rules alone (reasons 1–12): what CardBuilder#build runs.
217
+ def check_card(card)
218
+ Found.new.tap { |f| f.card(card) }.raise_first
219
+ end
220
+
221
+ # The tutor note's rules alone: what Reply#tutor_note runs.
222
+ def check_tutor_note(note)
223
+ Found.new.tap { |f| f.tutor_note(note) }.raise_first
224
+ end
225
+ end
226
+ end
227
+ end
@@ -0,0 +1,181 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Lingara
6
+ module Apps
7
+ # A manifest the upload would refuse, with the first rule it breaks.
8
+ # #rule is one of ManifestRules::RULES.
9
+ class ManifestError < StandardError
10
+ attr_reader :rule
11
+
12
+ def initialize(rule)
13
+ @rule = rule
14
+ super("the manifest breaks the #{rule} rule")
15
+ end
16
+ end
17
+
18
+ # The manifest's rules (ADR 30.9.26am D5), hand-written against the
19
+ # manifest's wire form, which is in no spec the view reads. Each refuses
20
+ # what the upload would refuse or normalise away where a kit can know it,
21
+ # in the order conformance/vectors/manifest.json describes; a refusal
22
+ # names the first broken rule.
23
+ module ManifestRules
24
+ NAME_MAX_CHARS = 40
25
+ DESCRIPTION_MAX_CHARS = 280
26
+ STORED_MAX_BYTES = 65_536
27
+
28
+ RULES = %i[manifest_version default_locale name description render_url slots context duplicate too_large].freeze
29
+
30
+ # The slots a manifest may name: the generated AppSlotName's values,
31
+ # without the generator's unknown-value placeholder.
32
+ SLOT_NAMES = (AppSlotName.all_vars - [AppSlotName::UNKNOWN_DEFAULT_OPEN_API]).freeze
33
+
34
+ # Zero-width characters, beyond the card rules' controls and bidi marks.
35
+ ZERO_WIDTH = /[\u200B-\u200F\uFEFF]/
36
+ RENDER_URL = %r{\Ahttps://[^/?#]}i
37
+
38
+ module_function
39
+
40
+ def localized?(value, max)
41
+ return false unless value.is_a?(Hash) && !value.empty?
42
+ value.each_value.all? do |v|
43
+ next false unless v.is_a?(String)
44
+ trimmed = Limits.trim(v)
45
+ trimmed.length.between?(1, max) && !Limits.control?(trimmed, false) && !trimmed.match?(ZERO_WIDTH)
46
+ end
47
+ end
48
+
49
+ def default_locale?(m)
50
+ locale = m["default_locale"]
51
+ return false unless locale.is_a?(String) && !locale.empty?
52
+ [m["name"], m["description"]].all? { |map| !map.is_a?(Hash) || map.key?(locale) }
53
+ end
54
+
55
+ # A list of allowed strings; absent passes only when +optional+.
56
+ def within?(m, key, allowed, optional)
57
+ return optional unless m.key?(key)
58
+ value = m[key]
59
+ return false unless value.is_a?(Array)
60
+ return false if value.empty? && !optional
61
+ value.all? { |v| v.is_a?(String) && allowed.include?(v) }
62
+ end
63
+
64
+ def duplicate?(m)
65
+ %w[slots context scopes].any? { |k| m[k].is_a?(Array) && m[k].uniq.size != m[k].size }
66
+ end
67
+
68
+ # The compact UTF-8 JSON of the seven stored keys, defaults filled.
69
+ def stored_bytes(m)
70
+ stored = {
71
+ "default_locale" => m["default_locale"], "name" => m["name"], "description" => m["description"],
72
+ "slots" => m["slots"], "context" => m["context"] || [], "scopes" => m["scopes"] || [],
73
+ "tutor_note" => m["tutor_note"].nil? ? false : m["tutor_note"]
74
+ }
75
+ JSON.generate(stored).bytesize
76
+ end
77
+
78
+ CHECKS = {
79
+ manifest_version: ->(m) { m["manifest_version"].is_a?(Integer) && m["manifest_version"] == 1 },
80
+ default_locale: ->(m) { default_locale?(m) },
81
+ name: ->(m) { localized?(m["name"], NAME_MAX_CHARS) },
82
+ description: ->(m) { localized?(m["description"], DESCRIPTION_MAX_CHARS) },
83
+ render_url: ->(m) { m["render_url"].is_a?(String) && m["render_url"].match?(RENDER_URL) },
84
+ slots: ->(m) { within?(m, "slots", SLOT_NAMES, false) },
85
+ context: ->(m) { within?(m, "context", CONTEXT_SLICE_KINDS, true) },
86
+ duplicate: ->(m) { !duplicate?(m) },
87
+ too_large: ->(m) { stored_bytes(m) <= STORED_MAX_BYTES }
88
+ }.freeze
89
+
90
+ # The first rule +manifest+ breaks, or nil. Takes any JSON value.
91
+ def first_broken(manifest)
92
+ m = manifest.is_a?(Hash) ? manifest : {}
93
+ RULES.find { |rule| !CHECKS.fetch(rule).call(m) }
94
+ end
95
+ end
96
+
97
+ # A fluent manifest. #build validates and returns the wire form (a Hash);
98
+ # #to_json writes the upload.
99
+ #
100
+ # Lingara::Apps.manifest.default_locale("en").name("Daily five").description("Five words.")
101
+ # .render_url("https://apps.example.com/lingara").slots("home.side").build
102
+ class ManifestBuilder
103
+ def initialize
104
+ @default_locale = ""
105
+ @name = ""
106
+ @description = ""
107
+ @render_url = ""
108
+ @slots = []
109
+ @context = []
110
+ @scopes = []
111
+ @tutor_note = false
112
+ @listed = false
113
+ end
114
+
115
+ def default_locale(locale) = set(:@default_locale, locale)
116
+
117
+ # A locale map, or a bare String meaning the default locale's.
118
+ def name(name) = set(:@name, name)
119
+
120
+ # A locale map, or a bare String meaning the default locale's.
121
+ def description(description) = set(:@description, description)
122
+
123
+ def render_url(url) = set(:@render_url, url)
124
+
125
+ # AppSlotName values.
126
+ def slots(*slots) = set(:@slots, slots)
127
+
128
+ # CONTEXT_SLICE_KINDS values.
129
+ def context(*kinds) = set(:@context, kinds)
130
+
131
+ def scopes(*scopes) = set(:@scopes, scopes)
132
+
133
+ # Whether the app's replies may carry a tutor note.
134
+ def tutor_note(enabled = true) = set(:@tutor_note, enabled)
135
+
136
+ # Whether the app appears in the catalogue; false unless set.
137
+ def listed(listed = true) = set(:@listed, listed)
138
+
139
+ # The manifest, or ManifestError naming the first rule it breaks.
140
+ def build
141
+ manifest = {
142
+ "manifest_version" => 1, "default_locale" => @default_locale, "name" => localized(@name),
143
+ "description" => localized(@description), "render_url" => @render_url, "slots" => @slots.dup,
144
+ "context" => @context.dup, "scopes" => @scopes.dup, "tutor_note" => @tutor_note, "listed" => @listed
145
+ }
146
+ Apps.validate_manifest(manifest)
147
+ manifest
148
+ end
149
+
150
+ # The validated manifest as the JSON the console accepts as an upload.
151
+ def to_json(*)
152
+ "#{JSON.pretty_generate(build)}\n"
153
+ end
154
+
155
+ private
156
+
157
+ def set(ivar, value)
158
+ instance_variable_set(ivar, value)
159
+ self
160
+ end
161
+
162
+ def localized(value)
163
+ value.is_a?(String) ? {@default_locale => value} : value
164
+ end
165
+ end
166
+
167
+ module_function
168
+
169
+ # Starts a manifest.
170
+ def manifest
171
+ ManifestBuilder.new
172
+ end
173
+
174
+ # Raises ManifestError naming the first rule +manifest+ (a Hash with
175
+ # String keys, as JSON.parse gives) breaks; nil when it keeps them all.
176
+ def validate_manifest(manifest)
177
+ rule = ManifestRules.first_broken(manifest)
178
+ raise ManifestError, rule if rule
179
+ end
180
+ end
181
+ end
@@ -0,0 +1,23 @@
1
+ # Generated by ruby/codegen/generate.rb from the app view. DO NOT EDIT.
2
+
3
+ module Lingara
4
+ module Apps
5
+ # The view's x-lingara-app-operations: the request messages a kit
6
+ # dispatches on (a request's `type`) and the reply message. The core's
7
+ # dispatch table is held to REQUESTS' keys by a unit test, so a third
8
+ # operation fails the build until the core handles it.
9
+ module Operations
10
+ RENDER = "app.render"
11
+ ACTION = "app.action"
12
+
13
+ # Each request message and the name of its generated request model.
14
+ REQUESTS = {
15
+ "app.render" => "AppRenderRequest",
16
+ "app.action" => "AppActionRequest"
17
+ }.freeze
18
+
19
+ # The reply every request expects: a card.
20
+ REPLY = "app.card"
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lingara
4
+ module Apps
5
+ # The Rack adapter (ADR 30.9.26am D2): a Rack-protocol endpoint over an
6
+ # App. The Rack protocol is a callable and a Hash, so the kit depends on
7
+ # no `rack` gem; mount it in any Rack server, Rails or Sinatra.
8
+ #
9
+ # # config.ru
10
+ # run Lingara::Apps::RackApp.new(app)
11
+ #
12
+ # It reads `rack.input` itself, as raw bytes and at most 64 KiB + 1 of
13
+ # them, before anything parses it, and hands the env to the library's
14
+ # verifier as the headers, as it is. Mount it where no middleware has
15
+ # already read or decoded the body: the signature covers the exact bytes
16
+ # Lingara sent.
17
+ class RackApp
18
+ def initialize(app)
19
+ raise ArgumentError, "RackApp wraps a Lingara::Apps::App" unless app.is_a?(App)
20
+ @app = app
21
+ end
22
+
23
+ def call(env)
24
+ input = env["rack.input"]
25
+ read = ->(limit) { input&.read(limit).to_s }
26
+ status, headers, body = @app.handle(env["REQUEST_METHOD"], env, read)
27
+ [status, headers.dup, body.empty? ? [] : [body]]
28
+ end
29
+ end
30
+ end
31
+ end