command_tower 0.22.0 → 0.23.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 (124) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/messaging/gallery_controller.rb +35 -0
  3. data/app/controllers/command_tower/admin/messaging/gallery_test_sends_controller.rb +54 -0
  4. data/app/controllers/command_tower/me/inbox_controller.rb +19 -4
  5. data/app/controllers/command_tower/messaging/unsubscribe_controller.rb +43 -0
  6. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +36 -1
  7. data/app/errors/command_tower/errors/messaging/announcement_type_not_supported_error.rb +23 -0
  8. data/app/errors/command_tower/errors/messaging/gallery_test_send_failed_error.rb +26 -0
  9. data/app/errors/command_tower/errors/messaging/gallery_test_send_impersonating_error.rb +23 -0
  10. data/app/errors/command_tower/errors/messaging/gallery_test_send_rate_limit_error.rb +25 -0
  11. data/app/errors/command_tower/errors/messaging/unsubscribe_rate_limit_error.rb +25 -0
  12. data/app/jobs/command_tower/messaging/communications/produce_recipient_job.rb +2 -2
  13. data/app/mailers/command_tower/messaging/channel_mailer.rb +2 -0
  14. data/app/models/command_tower/messaging/communication.rb +10 -0
  15. data/app/serializers/command_tower/serializers/admin/messaging/gallery_serializer.rb +67 -0
  16. data/app/services/command_tower/email_theme/resolver.rb +13 -12
  17. data/app/services/command_tower/messaging/accept/coordinator.rb +57 -4
  18. data/app/services/command_tower/messaging/accept/persister.rb +3 -0
  19. data/app/services/command_tower/messaging/accept/request_normalizer.rb +9 -4
  20. data/app/services/command_tower/messaging/accept/resolve_communication_slots.rb +114 -0
  21. data/app/services/command_tower/messaging/announcement_definition.rb +88 -0
  22. data/app/services/command_tower/messaging/contract/inbox.rb +65 -0
  23. data/app/services/command_tower/messaging/contract/mappers/communication_mapper.rb +9 -0
  24. data/app/services/command_tower/messaging/contract/requests/mark_viewed_for_communication.rb +21 -0
  25. data/app/services/command_tower/messaging/contract/requests/viewed_for_communication.rb +21 -0
  26. data/app/services/command_tower/messaging/contract/results/communication_result.rb +3 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_view_mark.rb +18 -0
  28. data/app/services/command_tower/messaging/definitions/document_builder.rb +157 -0
  29. data/app/services/command_tower/messaging/definitions/render_context.rb +18 -0
  30. data/app/services/command_tower/messaging/inbox/item_result.rb +5 -1
  31. data/app/services/command_tower/messaging/inbox/mutator.rb +17 -0
  32. data/app/services/command_tower/messaging/inbox/reader.rb +12 -0
  33. data/app/services/command_tower/messaging/inbox/scope.rb +8 -0
  34. data/app/services/command_tower/messaging/inbox.rb +8 -0
  35. data/app/services/command_tower/messaging/message_definition/metadata.rb +35 -0
  36. data/app/services/command_tower/messaging/message_definition.rb +151 -0
  37. data/app/services/command_tower/messaging/notification_types/declaration.rb +12 -1
  38. data/app/services/command_tower/messaging/notification_types/message_definition_checks.rb +143 -0
  39. data/app/services/command_tower/messaging/notification_types/registry.rb +2 -0
  40. data/app/services/command_tower/messaging/rendering/channel_renderer.rb +73 -6
  41. data/app/services/command_tower/messaging/rendering/compliance_footer.rb +80 -0
  42. data/app/services/command_tower/messaging/rendering/defined_email_renderer.rb +141 -0
  43. data/app/services/command_tower/messaging/rendering/inbox_document_renderer.rb +79 -4
  44. data/app/services/command_tower/messaging/rendering/rendered_payload.rb +13 -1
  45. data/app/services/command_tower/messaging/rendering/unsubscribe_headers.rb +51 -0
  46. data/app/services/command_tower/messaging/unsubscribe/token_verifier.rb +26 -0
  47. data/app/services/command_tower/services/messaging/announcements/resolve_produce_arguments.rb +74 -0
  48. data/app/services/command_tower/services/messaging/communications/explicit_copy_rule.rb +50 -0
  49. data/app/services/command_tower/services/messaging/communications/produce.rb +18 -4
  50. data/app/services/command_tower/services/messaging/communications/produce_many.rb +20 -2
  51. data/app/services/command_tower/services/messaging/gallery/channel_failed.rb +31 -0
  52. data/app/services/command_tower/services/messaging/gallery/check_test_send_rate_limit.rb +47 -0
  53. data/app/services/command_tower/services/messaging/gallery/list_gallery_types.rb +44 -0
  54. data/app/services/command_tower/services/messaging/gallery/preview_builder.rb +122 -0
  55. data/app/services/command_tower/services/messaging/gallery/preview_channels.rb +51 -0
  56. data/app/services/command_tower/services/messaging/gallery/preview_checks.rb +85 -0
  57. data/app/services/command_tower/services/messaging/gallery/preview_email.rb +56 -0
  58. data/app/services/command_tower/services/messaging/gallery/render_gallery_preview.rb +85 -0
  59. data/app/services/command_tower/services/messaging/gallery/test_send.rb +55 -0
  60. data/app/services/command_tower/services/messaging/inbox.rb +36 -8
  61. data/app/services/command_tower/services/messaging/unsubscribe/check_rate_limit.rb +57 -0
  62. data/app/services/command_tower/services/messaging/unsubscribe/issue_token.rb +25 -0
  63. data/app/services/command_tower/services/messaging/unsubscribe/opt_out_of_email.rb +65 -0
  64. data/app/services/command_tower/services/messaging/unsubscribe/verify_token.rb +42 -0
  65. data/app/services/command_tower/services/users/record_last_known_time_zone.rb +40 -0
  66. data/app/workflows/command_tower/workflows/admin/messaging/create_announcement_workflow.rb +16 -3
  67. data/app/workflows/command_tower/workflows/admin/messaging/gallery/index_workflow.rb +29 -0
  68. data/app/workflows/command_tower/workflows/admin/messaging/gallery/show_workflow.rb +40 -0
  69. data/app/workflows/command_tower/workflows/admin/messaging/gallery/test_send_workflow.rb +103 -0
  70. data/app/workflows/command_tower/workflows/messaging/communications/produce_recipient_workflow.rb +2 -2
  71. data/app/workflows/command_tower/workflows/messaging/error_mapping.rb +8 -1
  72. data/app/workflows/command_tower/workflows/messaging/inbox.rb +30 -5
  73. data/app/workflows/command_tower/workflows/messaging/unsubscribe/one_click_workflow.rb +56 -0
  74. data/app/workflows/command_tower/workflows/messaging/unsubscribe/preferences_redirect_workflow.rb +24 -0
  75. data/config/routes.rb +9 -0
  76. data/db/migrate/20261124000001_add_message_definition_columns_to_messaging_communications.rb +9 -0
  77. data/docs/admin_workspace.md +2 -1
  78. data/docs/api_reference.md +78 -20
  79. data/docs/audit.md +9 -0
  80. data/docs/authentication_authorization_guide.md +1 -1
  81. data/docs/bootstrap/09-rbac.md +2 -0
  82. data/docs/bootstrap/11-auth-client-path.md +1 -1
  83. data/docs/cookie_authentication_guide.md +2 -0
  84. data/docs/extending.md +4 -0
  85. data/docs/messaging_integration_guide.md +40 -15
  86. data/docs/principal_capabilities.md +2 -0
  87. data/docs/ui.md +64 -2
  88. data/docs/upgrades/0.23.0.md +64 -0
  89. data/docs/upgrades/README.md +1 -0
  90. data/lib/command_tower/authorization/default.yml +8 -0
  91. data/lib/command_tower/configuration/messaging/compliance.rb +47 -0
  92. data/lib/command_tower/configuration/messaging/config.rb +25 -0
  93. data/lib/command_tower/configuration/registry/admin_workspace/config.rb +9 -0
  94. data/lib/command_tower/configuration/registry/admin_workspace/tool_definition.rb +10 -1
  95. data/lib/command_tower/configuration/registry/audit/config.rb +38 -0
  96. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +2 -0
  97. data/lib/command_tower/current.rb +1 -0
  98. data/lib/command_tower/email_theme/default_ui_tokens.json +18 -0
  99. data/lib/command_tower/email_theme/palette.rb +75 -0
  100. data/lib/command_tower/email_theme/token_file.rb +81 -0
  101. data/lib/command_tower/engine.rb +7 -0
  102. data/lib/command_tower/execution.rb +2 -1
  103. data/lib/command_tower/install/baseline.rb +1 -0
  104. data/lib/command_tower/rspec/message_definition.rb +125 -0
  105. data/lib/command_tower/ui/document.rb +18 -4
  106. data/lib/command_tower/ui/email/renderer/text_nodes.rb +2 -1
  107. data/lib/command_tower/ui/email/renderer.rb +17 -5
  108. data/lib/command_tower/ui/email/text_part.rb +53 -0
  109. data/lib/command_tower/ui/fragments/markdown.rb +121 -0
  110. data/lib/command_tower/ui/markdown_subset/chunker.rb +91 -0
  111. data/lib/command_tower/ui/markdown_subset/inline.rb +86 -0
  112. data/lib/command_tower/ui/markdown_subset/segment.rb +15 -0
  113. data/lib/command_tower/ui/markdown_subset/walker.rb +129 -0
  114. data/lib/command_tower/ui/nodes/instant.rb +3 -0
  115. data/lib/command_tower/ui/redaction.rb +44 -0
  116. data/lib/command_tower/ui/required_facts/matchers/text.rb +22 -0
  117. data/lib/command_tower/ui/required_facts/matchers/time.rb +37 -0
  118. data/lib/command_tower/ui/required_facts/verdict.rb +54 -0
  119. data/lib/command_tower/ui/text_derivation.rb +18 -17
  120. data/lib/command_tower/ui/time_formatter.rb +5 -3
  121. data/lib/command_tower/ui.rb +6 -0
  122. data/lib/command_tower/version.rb +1 -1
  123. data/lib/command_tower.rb +2 -0
  124. metadata +78 -2
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Email
6
+ # The plain-text part of an email: the derived text with link targets (design G13).
7
+ # `TextDerivation` keeps only labels, so a plain-text reader could not follow a link or a
8
+ # button. Here each link span and button also writes a `label: https://...` line after its
9
+ # node's text. `textFallback` and channel slots stay on `TextDerivation`.
10
+ #
11
+ # `code` nodes are rejected by the renderer before this runs and `TextDerivation` excludes
12
+ # them, so a code value never reaches the text part.
13
+ module TextPart
14
+ class << self
15
+ # @param origin [String] http(s) origin that internal paths are prefixed with
16
+ def call(node, origin:, user_zone: CommandTower.config.ui.default_zone)
17
+ text_for(node, origin, user_zone)
18
+ end
19
+
20
+ private
21
+
22
+ def text_for(node, origin, user_zone)
23
+ case node
24
+ when Nodes::Container
25
+ join(node.children.map { |child| text_for(child, origin, user_zone) })
26
+ when Nodes::Button
27
+ target_line(node.label, node.action, origin) || node.label.to_s
28
+ when Nodes::Text, Nodes::Banner
29
+ join([TextDerivation.call(node, user_zone:), *link_lines(node, origin)])
30
+ when Nodes::Component then text_for(node.fallback, origin, user_zone)
31
+ else TextDerivation.call(node, user_zone:)
32
+ end
33
+ end
34
+
35
+ def link_lines(node, origin)
36
+ node.spans.filter_map do |span|
37
+ target_line(span.text, span.action, origin) if span.type == "link"
38
+ end
39
+ end
40
+
41
+ def target_line(label, action, origin)
42
+ url = action.path ? origin + action.path : action.href
43
+ "#{label}: #{url}" if url.present?
44
+ end
45
+
46
+ def join(parts)
47
+ parts.map(&:to_s).reject(&:empty?).join("\n")
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "kramdown"
4
+ require "command_tower/ui/markdown_subset/segment"
5
+ require "command_tower/ui/markdown_subset/inline"
6
+ require "command_tower/ui/markdown_subset/walker"
7
+ require "command_tower/ui/markdown_subset/chunker"
8
+
9
+ module CommandTower
10
+ module UI
11
+ module Fragments
12
+ # Renders an announcement body (a markdown subset) as catalog primitives.
13
+ # The kramdown AST is walked against an allowlist (MarkdownSubset::Walker
14
+ # and Inline): anything not named there is reduced to its plain text or
15
+ # dropped. Raw HTML never reaches the document. Rules: design ux/states.md
16
+ # section 6, G11 and G12; the supported subset is listed in docs/ui.md.
17
+ #
18
+ # d.fragment(Fragments::Markdown, source: "Hello **there**, see [classes](/classes).")
19
+ #
20
+ # Emits one `stack` of `text` nodes (nothing when the source has no
21
+ # renderable content). Long paragraphs are split at word boundaries. Output
22
+ # beyond `node_budget` nodes is cut and ends with a "…" paragraph.
23
+ class Markdown < Fragment
24
+ DEFAULT_NODE_BUDGET = 150
25
+ # The root stack and the closing ellipsis paragraph (text plus one span).
26
+ RESERVED_NODES = 3
27
+ ELLIPSIS = "…"
28
+
29
+ attribute :source, :string
30
+ attribute :node_budget, :integer, default: DEFAULT_NODE_BUDGET
31
+
32
+ validates :source, presence: true
33
+ validates :node_budget, numericality: { only_integer: true, greater_than: RESERVED_NODES }
34
+
35
+ def compose(builder)
36
+ blocks = fit_budget(chunked(MarkdownSubset::Walker.call(parse)))
37
+ return if blocks.empty?
38
+
39
+ builder.stack(gap: :md) { |stack| groups(blocks).each { |group| emit_group(stack, group) } }
40
+ end
41
+
42
+ private
43
+
44
+ def parse
45
+ Kramdown::Document.new(source, input: "kramdown", parse_block_html: true, parse_span_html: true,
46
+ html_to_native: false, auto_ids: false).root
47
+ end
48
+
49
+ def chunked(blocks)
50
+ blocks.flat_map do |block|
51
+ MarkdownSubset::Chunker.call(block.segments).map do |run|
52
+ MarkdownSubset::Block.new(block.variant, run, block.list_id)
53
+ end
54
+ end
55
+ end
56
+
57
+ # Keeps blocks while the node budget allows, then ends with "…".
58
+ def fit_budget(blocks)
59
+ seen = []
60
+ used = 0
61
+ kept = blocks.take_while do |block|
62
+ used += cost(block, seen)
63
+ used <= node_budget - RESERVED_NODES
64
+ end
65
+ return blocks if kept.length == blocks.length
66
+
67
+ log_truncation(kept.length, blocks.length)
68
+ kept + [MarkdownSubset::Block.new("body", [MarkdownSubset::Segment.new(ELLIPSIS)])]
69
+ end
70
+
71
+ # Nodes a block adds: its text, its spans, and the list stack on a list's first item.
72
+ def cost(block, seen)
73
+ new_list = block.list_id && seen.exclude?(block.list_id)
74
+ seen << block.list_id if new_list
75
+ 1 + block.segments.length + (new_list ? 1 : 0)
76
+ end
77
+
78
+ # Counts only, never content.
79
+ def log_truncation(kept, total)
80
+ Rails.logger.warn do
81
+ "[CommandTower::UI::Fragments::Markdown] cut at node budget (#{kept} of #{total} paragraphs kept)"
82
+ end
83
+ end
84
+
85
+ # List items share one group; every other block is its own group.
86
+ def groups(blocks)
87
+ blocks.slice_when { |a, b| a.list_id.nil? || a.list_id != b.list_id }.to_a
88
+ end
89
+
90
+ def emit_group(stack, group)
91
+ if group.first.list_id
92
+ stack.stack(gap: :xs) { |inner| group.each { |block| emit_text(inner, block) } }
93
+ else
94
+ emit_text(stack, group.first)
95
+ end
96
+ end
97
+
98
+ def emit_text(builder, block)
99
+ spans = block.segments.map { |segment| span_for(builder, segment) }
100
+ options = { variant: block.variant.to_sym }
101
+ options[:text_tone] = :secondary if block.variant == "subtitle"
102
+ builder.text(*spans, **options)
103
+ end
104
+
105
+ def span_for(builder, segment)
106
+ if segment.href
107
+ builder.link(segment.text, action: link_action(builder, segment.href))
108
+ elsif segment.strong
109
+ builder.strong(segment.text)
110
+ else
111
+ segment.text
112
+ end
113
+ end
114
+
115
+ def link_action(builder, href)
116
+ Hardening.internal_path?(href) ? builder.navigate(path: href) : builder.navigate(href:)
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module MarkdownSubset
6
+ # Splits styled text into runs that fit one `text` node: under the string
7
+ # limit and the span cap, cut at word boundaries (an unbroken string is
8
+ # cut at the limit). Returns arrays of Segments; no run is blank.
9
+ class Chunker
10
+ LIMIT = Limits::MAX_STRING_LENGTH - 1
11
+
12
+ def self.call(segments)
13
+ new.call(segments)
14
+ end
15
+
16
+ def call(segments)
17
+ @runs = []
18
+ reset
19
+ tokens(segments).each { |token| add(token) }
20
+ flush
21
+ @runs
22
+ end
23
+
24
+ private
25
+
26
+ def reset
27
+ @current = []
28
+ @length = 0
29
+ end
30
+
31
+ def add(token)
32
+ # No doubled whitespace (a dropped image or a break leaves some behind).
33
+ token.text = token.text.lstrip if open_whitespace?
34
+ return if token.text.empty?
35
+ return add_whitespace(token) if token.text.strip.empty?
36
+
37
+ flush if @length + token.text.length > LIMIT
38
+ append(token)
39
+ end
40
+
41
+ def open_whitespace?
42
+ @current.last&.text&.match?(/\s\z/)
43
+ end
44
+
45
+ # Span text may not be blank, so whitespace-only tokens join the previous span.
46
+ def add_whitespace(token)
47
+ return if @current.empty?
48
+
49
+ @current.last.text += token.text
50
+ @length += token.text.length
51
+ end
52
+
53
+ def append(token)
54
+ last = @current.last
55
+ if last && same_style?(last, token)
56
+ last.text += token.text
57
+ else
58
+ flush if @current.length >= Limits::MAX_SPANS
59
+ @current << token
60
+ end
61
+ @length += token.text.length
62
+ end
63
+
64
+ def flush
65
+ run = trim(@current)
66
+ @runs << run unless run.empty?
67
+ reset
68
+ end
69
+
70
+ def tokens(segments)
71
+ segments.flat_map do |segment|
72
+ segment.text.scan(/\s*\S+\s*|\s+/).flat_map do |word|
73
+ word.scan(/.{1,#{LIMIT}}/m).map { |piece| Segment.new(piece, segment.strong, segment.href) }
74
+ end
75
+ end
76
+ end
77
+
78
+ def same_style?(first, second)
79
+ first.strong == second.strong && first.href == second.href
80
+ end
81
+
82
+ def trim(run)
83
+ run = run.map(&:dup)
84
+ run.first&.text = run.first.text.lstrip
85
+ run.last&.text = run.last.text.rstrip
86
+ run.reject { |segment| segment.text.strip.empty? }
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module MarkdownSubset
6
+ # Allowlist walk over inline kramdown elements. Anything not named here
7
+ # is dropped (images, footnotes, math) or reduced to its text (emphasis,
8
+ # code). Links survive only when Hardening accepts the target.
9
+ class Inline
10
+ DROPPED_HTML = %w[script style].freeze
11
+ INLINE_HTML = %w[a b strong em i u span code small sub sup br abbr mark cite q s del ins].freeze
12
+ INLINE_TYPES = %i[text strong em a codespan br smart_quote typographic_sym entity footnote math
13
+ abbreviation img].freeze
14
+ SMART_QUOTES = { lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”" }.freeze
15
+ TYPOGRAPHIC = { mdash: "—", ndash: "–", hellip: "…", laquo: "«", raquo: "»", laquo_space: "« ",
16
+ raquo_space: " »" }.freeze
17
+
18
+ class << self
19
+ def segments(elements, strong: false, href: nil)
20
+ elements.flat_map { |element| for_element(element, strong:, href:) }
21
+ end
22
+
23
+ def plain_text(element)
24
+ return "" if element.type == :img
25
+ return element.value.to_s if %i[text codespan].include?(element.type)
26
+
27
+ segments(element.children).map(&:text).join
28
+ end
29
+
30
+ # True when the element belongs inside a paragraph rather than being a block.
31
+ def inline?(element)
32
+ return INLINE_TYPES.include?(element.type) unless element.type == :html_element
33
+
34
+ DROPPED_HTML.include?(element.value) || INLINE_HTML.include?(element.value)
35
+ end
36
+
37
+ private
38
+
39
+ def for_element(element, strong:, href:)
40
+ case element.type
41
+ when :text then [Segment.new(element.value.to_s.gsub(/\s*\n\s*/, " "), strong, href)]
42
+ when :strong then segments(element.children, strong: true, href:)
43
+ when :a then link(element, strong:)
44
+ when :html_element then html(element, strong:, href:)
45
+ when :em, :abbreviation then segments(element.children, strong:, href:)
46
+ else literal(element, strong:, href:)
47
+ end
48
+ end
49
+
50
+ def literal(element, strong:, href:)
51
+ text = literal_text(element)
52
+ text ? [Segment.new(text, strong, href)] : []
53
+ end
54
+
55
+ def literal_text(element)
56
+ case element.type
57
+ when :br then "\n"
58
+ when :codespan then element.value.to_s
59
+ when :entity then element.value.char
60
+ when :smart_quote then SMART_QUOTES[element.value]
61
+ when :typographic_sym then TYPOGRAPHIC[element.value]
62
+ end
63
+ end
64
+
65
+ def html(element, strong:, href:)
66
+ return [] if DROPPED_HTML.include?(element.value)
67
+
68
+ segments(element.children, strong: strong || %w[b strong].include?(element.value), href:)
69
+ end
70
+
71
+ def link(element, strong:)
72
+ target = element.attr["href"].to_s
73
+ label = segments(element.children, strong:)
74
+ return label unless safe_link?(target)
75
+
76
+ label.map { |segment| segment.href ? segment : Segment.new(segment.text, false, target) }
77
+ end
78
+
79
+ def safe_link?(target)
80
+ Hardening.internal_path?(target) || Hardening.external_href_code(target).nil?
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ # Helpers behind Fragments::Markdown: an allowlist walk over the kramdown
6
+ # AST (Walker, Inline) and a splitter that keeps text within limits (Chunker).
7
+ module MarkdownSubset
8
+ # A run of text with one style. `href` is a vetted link target or nil.
9
+ Segment = Struct.new(:text, :strong, :href)
10
+
11
+ # One output paragraph. `list_id` groups the items of one list.
12
+ Block = Struct.new(:variant, :segments, :list_id)
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module MarkdownSubset
6
+ # Allowlist walk over block-level kramdown elements. Returns Blocks;
7
+ # elements not listed in HANDLERS (hr, blank, comments, ...) are dropped.
8
+ class Walker
9
+ HEADING_VARIANTS = { 1 => "title", 2 => "title", 3 => "subtitle" }.freeze
10
+ LISTS = %i[ul ol].freeze
11
+ HANDLERS = {
12
+ p: :paragraph_block, header: :header_block, ul: :list_blocks, ol: :list_blocks,
13
+ codeblock: :code_block, table: :table_blocks, html_element: :html_block, raw: :raw_block,
14
+ blockquote: :container_blocks, dl: :container_blocks, dt: :container_blocks,
15
+ dd: :container_blocks, li: :container_blocks
16
+ }.freeze
17
+
18
+ def self.call(root)
19
+ new.call(root)
20
+ end
21
+
22
+ def initialize
23
+ @list_id = 0
24
+ end
25
+
26
+ def call(root)
27
+ blocks_of(root.children)
28
+ end
29
+
30
+ private
31
+
32
+ def blocks_of(children)
33
+ children.chunk { |child| Inline.inline?(child) }.flat_map do |inline, group|
34
+ inline ? text_block("body", group) : group.flat_map { |child| block_for(child) }
35
+ end
36
+ end
37
+
38
+ def block_for(element)
39
+ handler = HANDLERS[element.type]
40
+ handler ? send(handler, element) : []
41
+ end
42
+
43
+ def text_block(variant, children)
44
+ segments = Inline.segments(children)
45
+ blank?(segments) ? [] : [Block.new(variant, segments)]
46
+ end
47
+
48
+ def paragraph_block(element)
49
+ text_block("body", element.children)
50
+ end
51
+
52
+ def header_block(element)
53
+ text_block(HEADING_VARIANTS.fetch(element.options[:level].to_i, "body"), element.children)
54
+ end
55
+
56
+ def container_blocks(element)
57
+ blocks_of(element.children)
58
+ end
59
+
60
+ def html_block(element)
61
+ Inline::DROPPED_HTML.include?(element.value) ? [] : blocks_of(element.children)
62
+ end
63
+
64
+ def code_block(element)
65
+ literal_block(element.value.to_s.chomp)
66
+ end
67
+
68
+ # With parse_block_html the body is parsed; :raw is what is left over.
69
+ def raw_block(element)
70
+ literal_block(strip_tags(element.value.to_s).strip)
71
+ end
72
+
73
+ def literal_block(text)
74
+ text.strip.empty? ? [] : [Block.new("body", [Segment.new(text)])]
75
+ end
76
+
77
+ def strip_tags(html)
78
+ html.gsub(%r{<(script|style)\b[^>]*>.*?</\1\s*>}mi, "").gsub(/<[^>]*>/m, "")
79
+ end
80
+
81
+ # One paragraph per row, cells joined by a middle dot.
82
+ def table_blocks(table)
83
+ rows(table).flat_map do |row|
84
+ cells = row.children.map { |cell| Inline.plain_text(cell).strip }.reject(&:empty?)
85
+ cells.empty? ? [] : literal_block(cells.join(" · "))
86
+ end
87
+ end
88
+
89
+ def rows(element)
90
+ element.children.flat_map { |child| child.type == :tr ? [child] : rows(child) }
91
+ end
92
+
93
+ def list_blocks(list)
94
+ @list_id += 1
95
+ id = @list_id
96
+ list_items(list).map { |prefix, segments| Block.new("body", [Segment.new(prefix)] + segments, id) }
97
+ end
98
+
99
+ # Nested lists are flattened to one level. Returns [prefix, segments] pairs.
100
+ def list_items(list)
101
+ list.children.select { |child| child.type == :li }.each_with_index.flat_map do |item, index|
102
+ item_entries(item, item_prefix(list, index))
103
+ end
104
+ end
105
+
106
+ def item_entries(item, prefix)
107
+ nested, own = item.children.partition { |child| LISTS.include?(child.type) }
108
+ segments = item_segments(own)
109
+ head = blank?(segments) ? [] : [[prefix, segments]]
110
+ head + nested.flat_map { |inner| list_items(inner) }
111
+ end
112
+
113
+ def item_prefix(list, index)
114
+ list.type == :ol ? "#{index + 1}. " : "• "
115
+ end
116
+
117
+ def item_segments(children)
118
+ blocks_of(children).map(&:segments).each_with_index.flat_map do |segments, index|
119
+ index.zero? ? segments : [Segment.new(" ")] + segments
120
+ end
121
+ end
122
+
123
+ def blank?(segments)
124
+ segments.all? { |segment| segment.text.strip.empty? }
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
@@ -20,6 +20,8 @@ module CommandTower
20
20
  TYPE = "time"
21
21
  FORMAT = %w[short long date time countdown].freeze
22
22
  LABEL = %w[auto always never].freeze
23
+ # `zone: "user"` (or :user) means the recipient's zone, resolved at render time.
24
+ USER_ZONE = "user"
23
25
  UTC_ISO8601 = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\z/
24
26
 
25
27
  field :at, InstantAtType.new
@@ -48,6 +50,7 @@ module CommandTower
48
50
 
49
51
  def zone_is_known
50
52
  return errors.add(:zone, :blank) if zone.blank?
53
+ return if zone == USER_ZONE
51
54
 
52
55
  TZInfo::Timezone.get(zone)
53
56
  rescue TZInfo::InvalidTimezoneIdentifier
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ # Pure transform for impersonated inbox reads: every `code` node becomes a
6
+ # plain `text` node (variant body, textTone secondary, label dropped) so the
7
+ # code value never reaches the serialised document. Returns a new Document
8
+ # and never mutates its input.
9
+ #
10
+ # `impersonating:` must be exactly false to skip redaction; any other value
11
+ # (including nil, "unknown") redacts.
12
+ module Redaction
13
+ REPLACEMENT_TEXT = "Open the app to check in"
14
+
15
+ def self.call(document, impersonating:)
16
+ return document if impersonating == false
17
+
18
+ Document.new(root: redact(document.root), text_fallback: document.text_fallback)
19
+ end
20
+
21
+ def self.redact(node)
22
+ case node
23
+ when Nodes::Code then replacement
24
+ when Nodes::Container then copy_with(node, children: node.children.map { |child| redact(child) })
25
+ when Nodes::Component then copy_with(node, fallback: redact(node.fallback))
26
+ else node
27
+ end
28
+ end
29
+ private_class_method :redact
30
+
31
+ def self.copy_with(node, **attributes)
32
+ copy = node.dup
33
+ attributes.each { |name, value| copy.public_send(:"#{name}=", value) }
34
+ copy
35
+ end
36
+ private_class_method :copy_with
37
+
38
+ def self.replacement
39
+ Nodes::Text.new(spans: [REPLACEMENT_TEXT], variant: "body", text_tone: "secondary")
40
+ end
41
+ private_class_method :replacement
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module RequiredFacts
6
+ module Matchers
7
+ # Passes when the metadata value for `key` appears verbatim in the text.
8
+ # Host matcher protocol: `call(text:, metadata:, t:) -> Boolean`.
9
+ class Text
10
+ def initialize(key:)
11
+ @key = key.to_s
12
+ end
13
+
14
+ def call(text:, metadata:, **)
15
+ value = Verdict.fetch(metadata, @key)
16
+ !value.nil? && text.to_s.include?(value.to_s)
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module RequiredFacts
6
+ module Matchers
7
+ # Passes when the text contains the `:time`-preset rendering of the metadata
8
+ # instant (for example "6:00 AM PT") in the fact's zone. Every time-of-day
9
+ # preset contains that string. `zone` is a metadata key holding an IANA
10
+ # zone, `:user` (the render zone), or nil (also the render zone).
11
+ # Host matcher protocol: `call(text:, metadata:, t:) -> Boolean`.
12
+ class Time
13
+ def initialize(key:, zone:, render_zone:)
14
+ @key = key.to_s
15
+ @zone = zone
16
+ @render_zone = render_zone
17
+ end
18
+
19
+ def call(text:, metadata:, t:) # rubocop:disable Naming/MethodParameterName
20
+ value = Verdict.fetch(metadata, @key)
21
+ return false if value.nil?
22
+
23
+ text.to_s.include?(t.call(value, zone: zone_for(metadata), format: :time))
24
+ end
25
+
26
+ private
27
+
28
+ def zone_for(metadata)
29
+ return @render_zone if @zone.nil? || @zone.to_s == TimeFormatter::USER_ZONE
30
+
31
+ Verdict.fetch(metadata, @zone.to_s) || @render_zone
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module RequiredFacts
6
+ # Pure check that rendered texts express a message's required facts. Runs in
7
+ # specs and the gallery only, never on the send path.
8
+ #
9
+ # Verdict.call(texts: { sms_body: "..." }, metadata:, required_facts:, render_zone:)
10
+ # # => [{ channel: :sms_body, fact_key: :starts_at, passed: true }]
11
+ #
12
+ # `texts` maps channel name to text. Callers leave out channels that must not
13
+ # carry facts (`headline`, `pushover_title`). Each required fact is a Hash with
14
+ # `key:`, `matcher:` (`:text`, `:time`, or a host matcher responding to
15
+ # `call(text:, metadata:, t:)`), `zone:` (metadata key or `:user`) and `optional:`.
16
+ # An optional fact whose metadata value is absent yields no rows.
17
+ module Verdict
18
+ def self.call(texts:, metadata:, required_facts:, render_zone:)
19
+ t = translator(render_zone)
20
+
21
+ required_facts.flat_map do |fact|
22
+ key = fact.fetch(:key)
23
+ next [] if fact[:optional] && fetch(metadata, key.to_s).nil?
24
+
25
+ matcher = matcher_for(fact, render_zone)
26
+ texts.map do |channel, text|
27
+ { channel:, fact_key: key, passed: matcher.call(text:, metadata:, t:) == true }
28
+ end
29
+ end
30
+ end
31
+
32
+ def self.fetch(metadata, key)
33
+ metadata.key?(key) ? metadata[key] : metadata[key.to_sym]
34
+ end
35
+
36
+ def self.translator(render_zone)
37
+ lambda do |at, zone: render_zone, format: :short, label: :auto|
38
+ TimeFormatter.call(at:, zone:, format:, label:, user_zone: render_zone)
39
+ end
40
+ end
41
+ private_class_method :translator
42
+
43
+ def self.matcher_for(fact, render_zone)
44
+ case fact.fetch(:matcher)
45
+ when :text then Matchers::Text.new(key: fact.fetch(:key))
46
+ when :time then Matchers::Time.new(key: fact.fetch(:key), zone: fact[:zone], render_zone:)
47
+ else fact.fetch(:matcher)
48
+ end
49
+ end
50
+ private_class_method :matcher_for
51
+ end
52
+ end
53
+ end
54
+ end