typst-rails 0.1.0 → 0.2.2

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,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "typst_rails/diagnostics"
4
+
5
+ module TypstRails
6
+ # Error class for Typst-related errors.
7
+ #
8
+ # Raised when Typst compilation fails, when files cannot be created,
9
+ # or when other Typst-specific errors occur during rendering. Compilation
10
+ # failures raise the {CompileError} subclass, which carries Typst's
11
+ # diagnostics.
12
+ #
13
+ # @example Handling Typst errors
14
+ # begin
15
+ # renderer.render(nil, data)
16
+ # rescue TypstRails::Error => e
17
+ # Rails.logger.error "Typst compilation failed: #{e.message}"
18
+ # render plain: "PDF generation failed", status: 500
19
+ # end
20
+ class Error < StandardError; end
21
+
22
+ # Raised when Typst rejects a template.
23
+ #
24
+ # The message names the template and the location of the first error,
25
+ # followed by Typst's own output with the render's temporary paths
26
+ # replaced by the template's name. The parsed diagnostics are available
27
+ # as attributes.
28
+ #
29
+ # Line numbers count lines of the Typst source Typst compiled. For `.typ`
30
+ # views and the Sinatra and Rage helpers, that is the template after ERB
31
+ # evaluation, so a `<% %>` block that emits several lines (or none) can
32
+ # shift them relative to the file on disk. {#source_line} shows the
33
+ # compiled line.
34
+ #
35
+ # @example
36
+ # begin
37
+ # renderer.render(nil, data)
38
+ # rescue TypstRails::CompileError => e
39
+ # e.template #=> "app/views/reports/show.pdf.typ"
40
+ # e.line #=> 4
41
+ # e.column #=> 9
42
+ # e.diagnostics.first.message #=> "unknown variable: foo"
43
+ # end
44
+ class CompileError < Error
45
+ # @return [Array<Diagnostics::Diagnostic>] every error and warning Typst
46
+ # reported, in the order it printed them. Empty when the output could
47
+ # not be parsed.
48
+ attr_reader :diagnostics
49
+
50
+ # @return [String, nil] display name of the template, such as
51
+ # "app/views/reports/show.pdf.typ", or nil if none was given
52
+ attr_reader :template
53
+
54
+ # @return [String] Typst's raw output, with temporary paths rewritten
55
+ attr_reader :typst_message
56
+
57
+ # @return [Array<String>, nil] the command line the CLI backend ran, for
58
+ # debugging; nil for other backends
59
+ attr_reader :command
60
+
61
+ # @return [String, nil] the compiled source line the first error points
62
+ # at, when that error is in the template itself
63
+ attr_reader :source_line
64
+
65
+ # @param typst_message [String, nil] Typst's diagnostic output
66
+ # @param template [String, nil] display name of the template
67
+ # @param command [Array<String>, nil] command line that was run
68
+ # @param source [String, nil] the Typst source that was compiled, used
69
+ # to look up {#source_line}
70
+ def initialize(typst_message = nil, template: nil, command: nil, source: nil)
71
+ @typst_message = Diagnostics.clean(typst_message).strip
72
+ @template = template
73
+ @command = command
74
+ @diagnostics = Diagnostics.parse(@typst_message)
75
+ @source_line = find_source_line(source)
76
+ super(build_message)
77
+ end
78
+
79
+ # @return [Array<Diagnostics::Diagnostic>] the errors among {#diagnostics}
80
+ def errors
81
+ diagnostics.select(&:error?)
82
+ end
83
+
84
+ # @return [Array<Diagnostics::Diagnostic>] the warnings among {#diagnostics}
85
+ def warnings
86
+ diagnostics.select(&:warning?)
87
+ end
88
+
89
+ # @return [Integer, nil] line of the first error, counted from 1
90
+ def line
91
+ first_error&.line
92
+ end
93
+
94
+ # @return [Integer, nil] column of the first error, counted from 0 as
95
+ # Typst reports it
96
+ def column
97
+ first_error&.column
98
+ end
99
+
100
+ private
101
+
102
+ def first_error
103
+ errors.first
104
+ end
105
+
106
+ def template_name
107
+ template || Diagnostics::INLINE_SOURCE_NAME
108
+ end
109
+
110
+ def in_template?(diagnostic)
111
+ diagnostic&.path == template_name
112
+ end
113
+
114
+ def find_source_line(source)
115
+ return nil unless source && in_template?(first_error) && line&.positive?
116
+
117
+ source.to_s.lines[line - 1]&.chomp
118
+ end
119
+
120
+ def build_message
121
+ [summary, typst_message].reject(&:empty?).join("\n\n")
122
+ end
123
+
124
+ def summary
125
+ error = first_error
126
+ return template ? "Typst compilation failed for #{template}." : "Typst compilation failed." unless error
127
+
128
+ text = "Typst compilation failed"
129
+ text += " in #{error.location}" if error.location
130
+ text += ": #{error.message}"
131
+ if in_template?(error)
132
+ text += "\n(Line numbers count lines of the compiled Typst source, after any ERB evaluation.)"
133
+ elsif template
134
+ text += "\n(while rendering #{template})"
135
+ end
136
+ text
137
+ end
138
+ end
139
+ end
@@ -1,18 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module TypstRails
4
- # Detects which web framework (if any) is currently loaded
4
+ # Detects which web framework (if any) is currently loaded.
5
+ #
6
+ # Each predicate returns a real +true+ or +false+. `defined?` yields a
7
+ # String or nil rather than a boolean, so the results are coerced: callers
8
+ # that compare against +false+ or serialize the value would otherwise see
9
+ # nil when the framework is absent.
5
10
  module FrameworkDetection
11
+ # @return [Boolean] whether Rails is loaded and booted far enough to have
12
+ # an application object
6
13
  def self.rails?
7
- defined?(::Rails) && ::Rails.respond_to?(:application)
14
+ !!(defined?(::Rails) && ::Rails.respond_to?(:application))
8
15
  end
9
16
 
17
+ # @return [Boolean] whether Rage is loaded
10
18
  def self.rage?
11
- defined?(::Rage::Application)
19
+ !defined?(::Rage::Application).nil?
12
20
  end
13
21
 
22
+ # @return [Boolean] whether Sinatra is loaded
14
23
  def self.sinatra?
15
- defined?(::Sinatra::Base)
24
+ !defined?(::Sinatra::Base).nil?
16
25
  end
17
26
 
18
27
  def self.detected_framework
@@ -35,6 +35,7 @@ module TypstRails
35
35
  # `erb_engine.src` generates a string of Ruby code. This code, when executed,
36
36
  # evaluates the ERB template and appends results to the `eoutvar` (i.e., `@output_buffer`).
37
37
  erb_evaluation_code = erb_engine.src
38
+ renderer_args = renderer_arguments(template)
38
39
 
39
40
  # The string returned by this `call` method is the final piece of Ruby code
40
41
  # that ActionView will `instance_eval`.
@@ -43,26 +44,67 @@ module TypstRails
43
44
  # capturing the result. This allows dynamic Ruby evaluation within the .typ file.
44
45
  # 2. Passes the ERB-processed Typst source to our `TypstRails::Renderer`
45
46
  # which then handles the actual Typst compilation.
47
+ #
48
+ # Only the outermost .typ template compiles. A .typ partial (or any .typ
49
+ # template rendered from inside another one) returns its ERB-processed
50
+ # source, so the parent can splice it in and compile the whole document
51
+ # once. The flag lives on the view context, which every nested render
52
+ # shares.
46
53
  <<-RUBY_CODE
54
+ _typst_rails_outermost = !@_typst_rails_rendering
55
+ @_typst_rails_rendering = true
56
+
47
57
  # Preserve the current @output_buffer if one exists (e.g., if rendering a partial).
48
58
  # A new buffer is created for ERB processing of the Typst template to isolate its output.
49
59
  _original_typst_handler_output_buffer = @output_buffer
50
60
  @output_buffer = ActionView::OutputBuffer.new
51
61
 
52
- #{erb_evaluation_code}
53
-
54
- # After the above ERB code executes, @output_buffer contains the
55
- # ERB-processed Typst template source as a string.
56
- processed_typst_source = @output_buffer.to_s
62
+ begin
63
+ #{erb_evaluation_code}
57
64
 
58
- # Restore the original output buffer that was in place before this handler ran.
59
- @output_buffer = _original_typst_handler_output_buffer
65
+ # After the above ERB code executes, @output_buffer contains the
66
+ # ERB-processed Typst template source as a string.
67
+ processed_typst_source = @output_buffer.to_s
68
+ ensure
69
+ # Restore the original output buffer that was in place before this handler ran.
70
+ @output_buffer = _original_typst_handler_output_buffer
71
+ @_typst_rails_rendering = false if _typst_rails_outermost
72
+ end
60
73
 
61
- typst_renderer = ::TypstRails::Renderer.new(processed_typst_source)
62
- typst_renderer.render(self, local_assigns)
74
+ if _typst_rails_outermost
75
+ typst_renderer = ::TypstRails::Renderer.new(#{renderer_args})
76
+ typst_renderer.render(self, local_assigns)
77
+ else
78
+ processed_typst_source
79
+ end
63
80
  RUBY_CODE
64
81
  end
65
82
 
83
+ # Template methods that name the template, best first. short_identifier
84
+ # is the path relative to Rails.root.
85
+ TEMPLATE_NAME_METHODS = %i[short_identifier identifier virtual_path].freeze
86
+
87
+ # @param template [ActionView::Template]
88
+ # @return [String, nil] a name for the template in error messages, such
89
+ # as "app/views/reports/show.pdf.typ"
90
+ def self.template_display_name(template)
91
+ TEMPLATE_NAME_METHODS.each do |name|
92
+ next unless template.respond_to?(name)
93
+
94
+ value = template.public_send(name)
95
+ return value.to_s unless value.nil? || value.to_s.empty?
96
+ end
97
+ nil
98
+ end
99
+
100
+ # The template's name is computed once, here, and embedded in the
101
+ # generated code as a string literal.
102
+ def self.renderer_arguments(template)
103
+ name = template_display_name(template)
104
+ name ? "processed_typst_source, template: #{name.inspect}" : "processed_typst_source"
105
+ end
106
+ private_class_method :renderer_arguments
107
+
66
108
  # Indicates whether this template handler supports streaming.
67
109
  # Typst compilation generates a complete PDF file; it's not inherently a streaming process
68
110
  # where chunks of output can be sent progressively. Therefore, streaming is not supported.
@@ -12,7 +12,6 @@ module TypstRails
12
12
  # - Converting HTML to Markdown and Typst
13
13
  # - Converting Markdown to Typst syntax
14
14
  # - Including external Markdown files
15
- # - Sanitizing HTML for security
16
15
  # - URL encoding
17
16
  #
18
17
  # These helpers are included in the Renderer and available in Rails ERB templates
@@ -41,6 +40,14 @@ module TypstRails
41
40
  # - `<`, `>` (labels and references)
42
41
  # - `{`, `}` (code blocks)
43
42
  # - `@` (references)
43
+ # - `` ` `` (raw text)
44
+ # - `~` (non-breaking space)
45
+ # - `/` when it starts a comment (`//`, `/*`)
46
+ # - `-` when it starts a shorthand (`--`, `---`, `-?`)
47
+ #
48
+ # Characters that only mean something at the start of a line are escaped
49
+ # there: `=` (heading), `-` (list), `+` (numbered list), `/` (term list)
50
+ # and the `.` of `1.` (numbered list).
44
51
  #
45
52
  # @param text [String, nil] The text to escape
46
53
  # @return [String] The escaped text, or empty string if text is nil
@@ -65,7 +72,11 @@ module TypstRails
65
72
 
66
73
  # Escape special Typst characters
67
74
  # See: https://typst.app/docs/reference/syntax/
68
- text.gsub(/([#\$*_\[\]\\<>{}@])/, '\\\\\1')
75
+ text.gsub(/([#\$*_\[\]\\<>{}@`~])/, '\\\\\1')
76
+ .gsub(%r{/(?=[/*])}, "\\\\/")
77
+ .gsub(/-(?=[-?])/, "\\\\-")
78
+ .gsub(%r{^([ \t]*)([=+/-])}, '\\1\\\\\\2')
79
+ .gsub(/^([ \t]*\d+)\.(?=[ \t]|$)/, '\\1\\.')
69
80
  end
70
81
 
71
82
  # MARK: - HTML Conversion
@@ -142,9 +153,14 @@ module TypstRails
142
153
  # - Headings (`#` → `=`)
143
154
  # - Bold (`**text**` → `*text*`)
144
155
  # - Italic (`*text*` → `_text_`)
156
+ # - Bold+italic (`***text***` → `*_text_*`)
145
157
  # - Links (`[text](url)` → `#link("url")[text]`)
146
158
  # - Images (`![alt](url)` → `#image("url")`)
147
159
  #
160
+ # Inline code and fenced code blocks pass through untouched. Everything
161
+ # else is escaped, so text such as "#tag", "$5" or "me@example.com" reads
162
+ # as written rather than as Typst code, math or a reference.
163
+ #
148
164
  # @param markdown [String, nil] The Markdown text to convert
149
165
  # @return [String] Typst-compatible markup, or empty string if markdown is nil
150
166
  # @raise [ArgumentError] if markdown is not a String or nil
@@ -161,6 +177,10 @@ module TypstRails
161
177
  # markdown_to_typst("**bold** and *italic*")
162
178
  # # => "*bold* and _italic_"
163
179
  #
180
+ # @example Converting combined bold and italic
181
+ # markdown_to_typst("***important***")
182
+ # # => "*_important_*"
183
+ #
164
184
  # @example Converting links
165
185
  # markdown_to_typst("[Typst](https://typst.app)")
166
186
  # # => "#link(\"https://typst.app\")[Typst]"
@@ -170,43 +190,7 @@ module TypstRails
170
190
  return "" if markdown.nil?
171
191
  raise ArgumentError, "markdown must be a String" unless markdown.is_a?(String)
172
192
 
173
- result = markdown.dup
174
-
175
- # Convert Markdown headers to Typst headers
176
- # # Title -> = Title
177
- # ## Subtitle -> == Subtitle
178
- # etc.
179
- result.gsub!(/^(#{Regexp.quote("#")}{1,6})\s+(.+)$/) do
180
- "#{"=" * Regexp.last_match(1).length} #{Regexp.last_match(2)}"
181
- end
182
-
183
- # Convert Markdown bold to Typst bold, using placeholder bytes (\x01 text \x02)
184
- # so the italic pass below doesn't re-convert the resulting *text* markers.
185
- # **text** or __text__ -> *text*
186
- result.gsub!(/(\*\*|__)(.+?)\1/, "\x01\\2\x02")
187
-
188
- # Convert Markdown italic to Typst italic (underscore style)
189
- # *text* or _text_ -> _text_
190
- result.gsub!(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/, '_\1_')
191
- result.gsub!(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/, '_\1_')
192
-
193
- # Replace bold placeholders with Typst bold markers
194
- result.gsub!("\x01", "*")
195
- result.gsub!("\x02", "*")
196
-
197
- # Convert Markdown code to Typst code
198
- # `code` -> `code` (same in Typst)
199
-
200
- # Convert Markdown images (must run before links, since ![alt](url)
201
- # would otherwise be matched by the link pattern below)
202
- # ![alt](url) -> #image("url")
203
- result.gsub!(/!\[([^\]]*)\]\(([^)]+)\)/, '#image("\2")')
204
-
205
- # Convert Markdown links
206
- # [text](url) -> #link("url")[text]
207
- result.gsub!(/\[([^\]]+)\]\(([^)]+)\)/, '#link("\2")[\1]')
208
-
209
- result
193
+ MarkdownConverter.new(markdown).convert
210
194
  end
211
195
 
212
196
  # Reads and includes Markdown content, converting it to Typst syntax.
@@ -247,79 +231,6 @@ module TypstRails
247
231
  end
248
232
  end
249
233
 
250
- # MARK: - HTML Sanitization
251
-
252
- DEFAULT_ALLOWED_TAGS = %w[
253
- h1 h2 h3 h4 h5 h6 p br strong em u s del ins
254
- ul ol li blockquote pre code a img table thead
255
- tbody tr th td
256
- ].freeze
257
-
258
- DEFAULT_ALLOWED_ATTRIBUTES = %w[href src alt title].freeze
259
-
260
- # Sanitizes HTML before conversion to prevent XSS attacks.
261
- #
262
- # This method removes potentially dangerous tags and attributes from HTML
263
- # before conversion to Typst. It provides basic XSS protection by:
264
- # - Removing `<script>` and `<style>` tags
265
- # - Removing event handler attributes (onclick, onload, etc.)
266
- # - Optionally filtering to allowed tags and attributes
267
- #
268
- # @param html [String, nil] The HTML to sanitize
269
- # @param allowed_tags [Array<String>, nil] List of allowed HTML tags (uses defaults if nil)
270
- # @param allowed_attributes [Array<String>, nil] List of allowed attributes (uses defaults if nil)
271
- # @return [String] Sanitized HTML, or empty string if html is nil
272
- # @raise [ArgumentError] if html is not a String or nil
273
- #
274
- # @example Basic sanitization
275
- # sanitize_html("<script>alert('xss')</script><p>Safe content</p>")
276
- # # => "<p>Safe content</p>"
277
- #
278
- # @example Removing event handlers
279
- # sanitize_html('<div onclick="evil()">Click</div>')
280
- # # => "<div>Click</div>"
281
- #
282
- # @example Custom allowed tags
283
- # sanitize_html("<p>Text</p><img src='x'>", allowed_tags: %w[p])
284
- # # => "<p>Text</p>"
285
- #
286
- # @note This is basic sanitization. For production use with untrusted HTML,
287
- # consider using a dedicated sanitization library like Loofah or Sanitize
288
- def sanitize_html(html, allowed_tags: nil, allowed_attributes: nil)
289
- return "" if html.nil?
290
- raise ArgumentError, "html must be a String" unless html.is_a?(String)
291
-
292
- allowed_tags ||= DEFAULT_ALLOWED_TAGS
293
- allowed_attributes ||= DEFAULT_ALLOWED_ATTRIBUTES
294
-
295
- fragment = Nokogiri::HTML5.fragment(html)
296
- strip_disallowed_nodes(fragment, allowed_tags, allowed_attributes)
297
- fragment.to_html
298
- end
299
-
300
- private
301
-
302
- # Recursively removes tags not in +allowed_tags+ (keeping their text content)
303
- # and strips attributes not in +allowed_attributes+ from the tags that remain.
304
- def strip_disallowed_nodes(node, allowed_tags, allowed_attributes)
305
- node.children.each do |child|
306
- next strip_disallowed_nodes(child, allowed_tags, allowed_attributes) unless child.element?
307
-
308
- unless allowed_tags.include?(child.name.downcase)
309
- child.replace(child.children)
310
- next strip_disallowed_nodes(node, allowed_tags, allowed_attributes)
311
- end
312
-
313
- child.attribute_nodes.each do |attr|
314
- attr.remove unless allowed_attributes.include?(attr.name.downcase)
315
- end
316
-
317
- strip_disallowed_nodes(child, allowed_tags, allowed_attributes)
318
- end
319
- end
320
-
321
- public
322
-
323
234
  # MARK: - URL Encoding
324
235
 
325
236
  # URL-encodes text for safe use in links.
@@ -352,3 +263,6 @@ module TypstRails
352
263
  end
353
264
  end
354
265
  end
266
+
267
+ # Loaded after Helpers is defined, since the converter includes it.
268
+ require "typst_rails/markdown_converter"