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,294 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "set"
5
+
6
+ module TypstRails
7
+ # Base class for errors raised by TypstRails. Defined fully in
8
+ # typst_rails/renderer; declared here so this file can be loaded alone.
9
+ class Error < StandardError; end
10
+
11
+ # Raised when data bound for typst_data.json contains a value that has no
12
+ # faithful JSON form. It is a {TypstRails::Error}, so code that already
13
+ # rescues render failures handles it too.
14
+ #
15
+ # @example
16
+ # begin
17
+ # renderer.render(nil, { total: Money.new(100) })
18
+ # rescue TypstRails::SerializationError => e
19
+ # e.path #=> "locals.total"
20
+ # e.reason #=> "is a Money, which is not JSON-serializable"
21
+ # end
22
+ class SerializationError < Error
23
+ # @return [String] Where the value sits, such as "locals.items[0].amount"
24
+ attr_reader :path
25
+
26
+ # @return [String] What is wrong with the value, without the path or hint
27
+ attr_reader :reason
28
+
29
+ # @param path [String] Where the value sits in the data
30
+ # @param reason [String] What is wrong with the value
31
+ # @param hint [String, nil] How to fix it, appended to the message
32
+ def initialize(path, reason, hint = nil)
33
+ @path = path
34
+ @reason = reason
35
+ super([summary, hint].compact.join(" "))
36
+ end
37
+
38
+ # @return [String] The path and reason, without the hint
39
+ def summary
40
+ "#{path} #{reason}."
41
+ end
42
+ end
43
+
44
+ # Converts Ruby values into plain JSON data (Hash with String keys, Array,
45
+ # String, Integer, finite Float, true, false, nil) for typst_data.json.
46
+ #
47
+ # Encoding the value with to_json directly is not safe: any object responds
48
+ # to it, so a value with no sensible JSON form still produces output. Plain
49
+ # JSON writes the object's #to_s, and ActiveSupport's Object#as_json writes
50
+ # its instance variables, so the template quietly receives "#<Money...>" or
51
+ # {} instead of an error. This class accepts only values it can convert
52
+ # faithfully and raises {SerializationError}, naming the key path, for the
53
+ # rest.
54
+ #
55
+ # Conversion rules:
56
+ # - nil, true, false, Integer and String pass through. A String must be
57
+ # valid UTF-8 (a binary String holding valid UTF-8 bytes is relabeled).
58
+ # - Symbol becomes a String.
59
+ # - A finite Float passes through; NaN and Infinity raise.
60
+ # - BigDecimal becomes a String, such as "19.99", to keep its exact value.
61
+ # This matches ActiveSupport, so a decimal column reads the same whether it
62
+ # arrives bare or inside a model. In Typst, use decimal(data.total) or
63
+ # float(data.total).
64
+ # - Other Numerics (Rational, Complex) raise.
65
+ # - Time, Date, DateTime and ActiveSupport::TimeWithZone become ISO 8601
66
+ # strings, without fractional seconds.
67
+ # - Hash keys must be Strings, Symbols or Numerics, and become Strings.
68
+ # Values are converted recursively.
69
+ # - Array and Set elements are converted recursively.
70
+ # - Any other object is converted with #as_json when its class defines one
71
+ # deliberately, or else with #to_h when its class defines that, and the
72
+ # result is converted recursively. The generic as_json that ActiveSupport
73
+ # puts on Object, and the ones on Kernel, BasicObject, Enumerable, IO and
74
+ # Numeric, do not count. Struct and Data use #to_h, because ActiveSupport's
75
+ # as_json for them would pass their members through the generic fallback.
76
+ # - Anything else raises.
77
+ #
78
+ # @example
79
+ # TypstRails::DataSerializer.normalize({ due: Date.new(2024, 3, 9), tags: Set[:a] })
80
+ # #=> { "due" => "2024-03-09", "tags" => ["a"] }
81
+ class DataSerializer
82
+ # Owners of #as_json that do not show a deliberate JSON form. Object holds
83
+ # ActiveSupport's fallback (active_support/core_ext/object/json), which
84
+ # dumps instance variables. ActiveSupport also defines as_json on
85
+ # Enumerable (to_a, which never ends for an endless Enumerator), IO (its
86
+ # #to_s), Numeric (self, so Rational stays Rational), Struct and Data.
87
+ # Ruby 2.7 still has the old, deprecated ::Data, which warns when named.
88
+ IGNORED_AS_JSON_OWNERS = [Object, Kernel, BasicObject, Enumerable, IO, Numeric, Struct,
89
+ (::Data if RUBY_VERSION >= "3.2")].compact.freeze
90
+
91
+ # Owners of #to_h that do not show a deliberate Hash form. Enumerable#to_h
92
+ # works only on pairs and would enumerate an IO or Enumerator.
93
+ IGNORED_TO_H_OWNERS = [Object, Kernel, BasicObject, Enumerable].freeze
94
+
95
+ # Nesting limit, so a #to_h or #as_json that returns a fresh object every
96
+ # time cannot recurse until the stack overflows.
97
+ MAX_DEPTH = 100
98
+
99
+ # Default advice appended to errors about unsupported objects.
100
+ CONVERT_HINT = "Convert it to a String, Number, Hash, or Array before rendering, " \
101
+ "or define as_json or to_h on its class to return plain data."
102
+
103
+ # Keys that can be written after a dot in a key path.
104
+ PLAIN_KEY = /\A[A-Za-z_][A-Za-z0-9_]*\z/.freeze
105
+
106
+ # Converts +value+ into plain JSON data.
107
+ #
108
+ # @param value [Object] The value to convert
109
+ # @param path [String] The name used for +value+ in error messages
110
+ # @return [Object] Plain JSON data
111
+ # @raise [SerializationError] if +value+, or anything inside it, has no
112
+ # faithful JSON form
113
+ def self.normalize(value, path: "data")
114
+ new.normalize(value, path)
115
+ end
116
+
117
+ # Extends a key path with a Hash key.
118
+ #
119
+ # @param path [String] The path of the Hash
120
+ # @param key [Object] The key
121
+ # @return [String] e.g. "locals.title" or 'locals["first name"]'
122
+ def self.child_path(path, key)
123
+ name = key.to_s
124
+ name.match?(PLAIN_KEY) ? "#{path}.#{name}" : "#{path}[#{name.inspect}]"
125
+ end
126
+
127
+ def initialize
128
+ @in_progress = {}.compare_by_identity
129
+ end
130
+
131
+ # @param value [Object] The value to convert
132
+ # @param path [String] The name used for +value+ in error messages
133
+ # @param depth [Integer] Current nesting depth
134
+ # @return [Object] Plain JSON data
135
+ # @raise [SerializationError] if the value has no faithful JSON form
136
+ def normalize(value, path, depth = 0)
137
+ raise SerializationError.new(path, "is nested more than #{MAX_DEPTH} levels deep") if depth > MAX_DEPTH
138
+
139
+ case value
140
+ when nil, true, false, Integer then value
141
+ when String then normalize_string(value, path)
142
+ when Symbol then value.to_s
143
+ when Float then normalize_float(value, path)
144
+ when Hash then guard_cycle(value, path) { normalize_hash(value, path, depth) }
145
+ when Array, Set then guard_cycle(value, path) { normalize_list(value, path, depth) }
146
+ else normalize_other(value, path, depth)
147
+ end
148
+ end
149
+
150
+ private
151
+
152
+ def normalize_string(value, path)
153
+ return value if value.encoding == Encoding::UTF_8 && value.valid_encoding?
154
+
155
+ utf8 = to_utf8(value)
156
+ return utf8 if utf8
157
+
158
+ raise SerializationError.new(path, "is a String in #{value.encoding} that has no valid UTF-8 form",
159
+ "Fix its encoding with String#encode or String#scrub.")
160
+ end
161
+
162
+ # Binary strings are relabeled rather than transcoded, so UTF-8 bytes read
163
+ # with File.binread still pass, as they did with to_json.
164
+ def to_utf8(value)
165
+ if value.encoding == Encoding::BINARY
166
+ relabeled = value.dup.force_encoding(Encoding::UTF_8)
167
+ relabeled if relabeled.valid_encoding?
168
+ elsif value.valid_encoding?
169
+ value.encode(Encoding::UTF_8)
170
+ end
171
+ rescue EncodingError
172
+ nil
173
+ end
174
+
175
+ def normalize_list(list, path, depth)
176
+ list.each_with_index.map { |item, index| normalize(item, "#{path}[#{index}]", depth + 1) }
177
+ end
178
+
179
+ def normalize_float(value, path)
180
+ return value if value.finite?
181
+
182
+ raise SerializationError.new(path, "is #{value}, which JSON cannot represent",
183
+ "Replace it with nil or a finite number.")
184
+ end
185
+
186
+ def normalize_hash(hash, path, depth)
187
+ hash.each_with_object({}) do |(key, value), result|
188
+ name = hash_key(key, path)
189
+ if result.key?(name)
190
+ raise SerializationError.new(path, "has more than one key that becomes #{name.inspect} in JSON",
191
+ "Keep only one of them.")
192
+ end
193
+
194
+ result[name] = normalize(value, self.class.child_path(path, name), depth + 1)
195
+ end
196
+ end
197
+
198
+ def hash_key(key, path)
199
+ case key
200
+ when String, Symbol, Numeric then key.to_s
201
+ else
202
+ raise SerializationError.new(path, "has a key that is #{a_class_name(key)}, but JSON object keys " \
203
+ "must be Strings, Symbols, or Numbers", "Convert the key to a String.")
204
+ end
205
+ end
206
+
207
+ def normalize_other(value, path, depth)
208
+ unless Kernel === value # rubocop:disable Style/CaseEquality -- BasicObject has no #is_a?
209
+ raise SerializationError.new(path, "is a BasicObject, which is not JSON-serializable", CONVERT_HINT)
210
+ end
211
+
212
+ return value.iso8601 if time_like?(value)
213
+ return normalize_big_decimal(value, path) if big_decimal?(value)
214
+
215
+ if value.is_a?(Numeric)
216
+ raise SerializationError.new(path, "is #{a_class_name(value)}, which JSON cannot represent exactly",
217
+ "Convert it to an Integer, Float, or BigDecimal.")
218
+ end
219
+
220
+ converter = converter_for(value)
221
+ unless converter
222
+ raise SerializationError.new(path, "is #{a_class_name(value)}, which is not JSON-serializable", CONVERT_HINT)
223
+ end
224
+
225
+ guard_cycle(value, path) { normalize(convert(value, converter, path), path, depth + 1) }
226
+ end
227
+
228
+ # ActiveSupport::TimeWithZone is not a Time subclass, but its #is_a?
229
+ # answers true for Time, which `case`/`when` would not consult.
230
+ def time_like?(value)
231
+ value.is_a?(Time) || value.is_a?(Date)
232
+ end
233
+
234
+ def big_decimal?(value)
235
+ defined?(::BigDecimal) && value.is_a?(::BigDecimal)
236
+ end
237
+
238
+ def normalize_big_decimal(value, path)
239
+ return value.to_s("F") if value.finite?
240
+
241
+ raise SerializationError.new(path, "is a BigDecimal #{value}, which JSON cannot represent",
242
+ "Replace it with nil or a finite number.")
243
+ end
244
+
245
+ def converter_for(value)
246
+ if defined_by_class?(value, :as_json, IGNORED_AS_JSON_OWNERS)
247
+ :as_json
248
+ elsif defined_by_class?(value, :to_h, IGNORED_TO_H_OWNERS)
249
+ :to_h
250
+ end
251
+ end
252
+
253
+ def defined_by_class?(value, name, ignored_owners)
254
+ value.respond_to?(name) && !ignored_owners.include?(value.method(name).owner)
255
+ rescue NameError
256
+ false
257
+ end
258
+
259
+ def convert(value, converter, path)
260
+ result = value.public_send(converter)
261
+ if result.equal?(value)
262
+ raise SerializationError.new(path, "is #{a_class_name(value)} whose #{converter} returns itself")
263
+ end
264
+
265
+ result
266
+ rescue SerializationError
267
+ raise
268
+ rescue StandardError => e
269
+ raise SerializationError.new(path, "is #{a_class_name(value)} whose #{converter} raised #{e.class}: #{e.message}")
270
+ end
271
+
272
+ def guard_cycle(value, path)
273
+ raise SerializationError.new(path, "contains itself, which JSON cannot represent") if @in_progress.key?(value)
274
+
275
+ @in_progress[value] = true
276
+ begin
277
+ yield
278
+ ensure
279
+ @in_progress.delete(value)
280
+ end
281
+ end
282
+
283
+ # @return [String] e.g. "a Money" or "an Object"
284
+ def a_class_name(value)
285
+ name = class_name(value)
286
+ "#{name.match?(/\A[AEIOU]/) ? "an" : "a"} #{name}"
287
+ end
288
+
289
+ def class_name(value)
290
+ klass = value.class
291
+ klass.name || klass.inspect
292
+ end
293
+ end
294
+ end
@@ -0,0 +1,284 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypstRails
4
+ # Parsing and path rewriting for the diagnostics Typst prints when it
5
+ # compiles a document.
6
+ #
7
+ # Typst reports problems in one of two layouts. The default, "human", is
8
+ # what both the `typst` CLI and the `typst` gem produce:
9
+ #
10
+ # error: unknown variable: foo
11
+ # ┌─ template.typ:4:9
12
+ # │
13
+ # 4 │ #let x = foo(1)
14
+ # │ ^^^
15
+ # │
16
+ # = hint: ...
17
+ #
18
+ # The CLI can also emit `--diagnostic-format short`, one line per
19
+ # diagnostic, without hints or source excerpts:
20
+ #
21
+ # template.typ:4:9: error: unknown variable: foo
22
+ #
23
+ # {.parse} understands both. Parsing is best-effort: text it does not
24
+ # recognize is skipped, so callers always keep the raw output as well.
25
+ module Diagnostics
26
+ # One error or warning reported by Typst.
27
+ #
28
+ # @!attribute [r] severity
29
+ # @return [Symbol] `:error` or `:warning`
30
+ # @!attribute [r] message
31
+ # @return [String] the diagnostic text, without the severity prefix
32
+ # @!attribute [r] path
33
+ # @return [String, nil] the file the diagnostic points at, if any
34
+ # @!attribute [r] line
35
+ # @return [Integer, nil] 1-based line number
36
+ # @!attribute [r] column
37
+ # @return [Integer, nil] column number as Typst reports it, counted
38
+ # from 0 (Typst 0.15 prints the first column of a line as 0)
39
+ # @!attribute [r] hints
40
+ # @return [Array<String>] hints Typst attached to the diagnostic
41
+ Diagnostic = Struct.new(:severity, :message, :path, :line, :column, :hints, keyword_init: true) do
42
+ # @return [Boolean] whether this is an error
43
+ def error?
44
+ severity == :error
45
+ end
46
+
47
+ # @return [Boolean] whether this is a warning
48
+ def warning?
49
+ severity == :warning
50
+ end
51
+
52
+ # @return [String, nil] "path:line:column", or as much of it as is known
53
+ def location
54
+ return nil unless path
55
+
56
+ [path, line, column].compact.join(":")
57
+ end
58
+
59
+ # @return [String] a one-line summary, e.g.
60
+ # "app/views/reports/show.pdf.typ:4:9: error: unknown variable: foo"
61
+ def to_s
62
+ [location, "#{severity}: #{message}"].compact.join(": ")
63
+ end
64
+ end
65
+
66
+ # Name used for the main template when no display name is known, for
67
+ # example when a Renderer is built from a string.
68
+ INLINE_SOURCE_NAME = "(inline source)"
69
+
70
+ HEADER = /\A(error|warning): (.*)\z/.freeze
71
+ LOCATION = /\A\s*┌─ (.+):(\d+):(\d+)\s*\z/.freeze
72
+ HINT = /\A\s*= hint: (.*)\z/.freeze
73
+ SHORT = /\A([^\s│][^│]*?):(\d+):(\d+): (error|warning): (.*)\z/.freeze
74
+ # Headers for secondary notes, such as the call trace the `typst` gem
75
+ # prints as "help: while calling `f`". Their locations belong to the
76
+ # note, not to the preceding diagnostic.
77
+ OTHER_HEADER = /\A[a-z]+(\[[^\]]*\])?: /.freeze
78
+ ANSI_ESCAPE = /\e\[[0-9;]*[A-Za-z]/.freeze
79
+ private_constant :HEADER, :LOCATION, :HINT, :SHORT, :OTHER_HEADER, :ANSI_ESCAPE
80
+
81
+ class << self
82
+ # Parses Typst diagnostic output.
83
+ #
84
+ # @param text [String, nil] stderr from the CLI, or the message of an
85
+ # exception raised by the `typst` gem
86
+ # @return [Array<Diagnostic>] the diagnostics found, in the order Typst
87
+ # printed them; empty if none were recognized
88
+ def parse(text)
89
+ diagnostics = []
90
+ current = nil
91
+
92
+ clean(text).each_line do |raw_line|
93
+ line = raw_line.chomp
94
+ current = parse_line(line, current, diagnostics)
95
+ end
96
+
97
+ diagnostics
98
+ rescue StandardError
99
+ diagnostics || []
100
+ end
101
+
102
+ # Normalizes diagnostic text: valid UTF-8, no terminal color codes.
103
+ #
104
+ # @param text [String, nil]
105
+ # @return [String]
106
+ def clean(text)
107
+ text = text.to_s.dup
108
+ text.force_encoding(Encoding::UTF_8)
109
+ text = text.scrub unless text.valid_encoding?
110
+ text.gsub(ANSI_ESCAPE, "")
111
+ end
112
+
113
+ # The default {TypstRails::Configuration#on_warning} handler. Logs the
114
+ # warnings through Rails.logger when it is available, and with
115
+ # Kernel#warn otherwise.
116
+ #
117
+ # @param warnings [Array<Diagnostic>]
118
+ # @param template [String, nil] display name of the template
119
+ # @return [void]
120
+ def log_warnings(warnings, template)
121
+ return if warnings.nil? || warnings.empty?
122
+
123
+ subject = template ? " in #{template}" : ""
124
+ noun = warnings.size == 1 ? "warning" : "warnings"
125
+ message = "TypstRails: Typst reported #{warnings.size} #{noun}#{subject}:\n" +
126
+ warnings.map { |w| " #{w}" }.join("\n")
127
+
128
+ if defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
129
+ ::Rails.logger.warn(message)
130
+ else
131
+ Kernel.warn(message)
132
+ end
133
+ nil
134
+ end
135
+
136
+ private
137
+
138
+ # Returns the diagnostic that following location and hint lines
139
+ # belong to, or nil when they belong to something else.
140
+ def parse_line(line, current, diagnostics)
141
+ if (match = HEADER.match(line))
142
+ start_diagnostic(diagnostics, match[1], match[2])
143
+ elsif (match = SHORT.match(line))
144
+ start_diagnostic(diagnostics, match[4], match[5], match.captures[0, 3])
145
+ elsif OTHER_HEADER.match?(line)
146
+ nil
147
+ else
148
+ annotate(current, line)
149
+ current
150
+ end
151
+ end
152
+
153
+ # @param location [Array(String, String, String)] path, line and column
154
+ def start_diagnostic(diagnostics, severity, message, location = [])
155
+ path, line, column = location
156
+ diagnostic = Diagnostic.new(
157
+ severity: severity.to_sym, message: message, path: path,
158
+ line: line&.to_i, column: column&.to_i, hints: []
159
+ )
160
+ diagnostics << diagnostic
161
+ diagnostic
162
+ end
163
+
164
+ def annotate(diagnostic, line)
165
+ return unless diagnostic
166
+
167
+ if diagnostic.path.nil? && (match = LOCATION.match(line))
168
+ diagnostic.path = match[1]
169
+ diagnostic.line = match[2].to_i
170
+ diagnostic.column = match[3].to_i
171
+ elsif (match = HINT.match(line))
172
+ diagnostic.hints << match[1]
173
+ end
174
+ end
175
+ end
176
+
177
+ # Replaces the paths of a render's temporary working directory in Typst
178
+ # output with names that mean something to the developer.
179
+ #
180
+ # Each render compiles a copy of the template in a fresh directory, such
181
+ # as /tmp/typst_rails_20261120-1234-abcd/template.typ, and Typst prints
182
+ # paths relative to the process's working directory. This class maps
183
+ # them back:
184
+ #
185
+ # - the template itself becomes its display name (for example
186
+ # "app/views/reports/show.pdf.typ"), or {INLINE_SOURCE_NAME};
187
+ # - other files in the working directory become relative to it;
188
+ # - files elsewhere under the Typst root become root-relative ("/lib.typ"),
189
+ # the form Typst source uses to refer to them;
190
+ # - anything else becomes an absolute path.
191
+ #
192
+ # @api private
193
+ class PathRewriter
194
+ # "┌─ path:line:col" in the human format.
195
+ LOCATION_LINE = /^(\s*┌─ )(.+):(\d+):(\d+)([ \t]*)$/.freeze
196
+ # "while calling `f` at path:line:col" in the CLI's call traces.
197
+ TRACE_LINE = /^(\s+[^\s│][^│\n]* at )(.+):(\d+):(\d+)([ \t]*)$/.freeze
198
+ # "path:line:col: error: ..." in the short format.
199
+ SHORT_LINE = /^([^\s│][^│\n]*?):(\d+):(\d+)(: (?:error|warning): )/.freeze
200
+ private_constant :LOCATION_LINE, :TRACE_LINE, :SHORT_LINE
201
+
202
+ # @param typ_path [String] the template file Typst compiled
203
+ # @param run_dir [String] the render's working directory
204
+ # @param root [String] the Typst root directory
205
+ # @param template [String, nil] display name for the template
206
+ # @param base_dir [String] directory Typst's relative paths are
207
+ # relative to (the process's working directory)
208
+ def initialize(typ_path:, run_dir:, root:, template: nil, base_dir: Dir.pwd)
209
+ @base_dir = base_dir
210
+ @typ_paths = variants(typ_path)
211
+ @run_dirs = variants(run_dir)
212
+ @roots = variants(root)
213
+ @template_name = template || INLINE_SOURCE_NAME
214
+ end
215
+
216
+ # @param text [String, nil] Typst diagnostic output
217
+ # @return [String] the text with working-directory paths replaced
218
+ def rewrite(text)
219
+ text = Diagnostics.clean(text)
220
+ text = text.gsub(LOCATION_LINE) { "#{Regexp.last_match(1)}#{location_suffix(Regexp.last_match)}" }
221
+ text = text.gsub(TRACE_LINE) { "#{Regexp.last_match(1)}#{location_suffix(Regexp.last_match)}" }
222
+ text = text.gsub(SHORT_LINE) do
223
+ match = Regexp.last_match
224
+ "#{display_path(match[1])}:#{match[2]}:#{match[3]}#{match[4]}"
225
+ end
226
+ strip_run_dir(text)
227
+ end
228
+
229
+ # @param path [String] a path as Typst printed it
230
+ # @return [String] the path to show the developer
231
+ def display_path(path)
232
+ absolute = canonical(File.expand_path(path, @base_dir))
233
+ return @template_name if @typ_paths.include?(absolute)
234
+
235
+ relative_to(absolute, @run_dirs) ||
236
+ root_relative(absolute) ||
237
+ absolute
238
+ end
239
+
240
+ private
241
+
242
+ def location_suffix(match)
243
+ "#{display_path(match[2])}:#{match[3]}:#{match[4]}#{match[5]}"
244
+ end
245
+
246
+ # Absolute mentions, such as "file not found (searched at
247
+ # /tmp/typst_rails_x/logo.png)", are shown relative to the template,
248
+ # which is how the template refers to them.
249
+ def strip_run_dir(text)
250
+ @typ_paths.each { |path| text = text.gsub(path, @template_name) }
251
+ @run_dirs.each { |dir| text = text.gsub("#{dir}#{File::SEPARATOR}", "") }
252
+ text
253
+ end
254
+
255
+ def relative_to(path, dirs)
256
+ dirs.each do |dir|
257
+ prefix = "#{dir}#{File::SEPARATOR}"
258
+ return path.delete_prefix(prefix) if path.start_with?(prefix)
259
+ end
260
+ nil
261
+ end
262
+
263
+ def root_relative(path)
264
+ relative = relative_to(path, @roots)
265
+ relative && "#{File::SEPARATOR}#{relative}"
266
+ end
267
+
268
+ # Typst may print the physical path of a directory reached through a
269
+ # symlink (macOS's /var -> /private/var), so both spellings match.
270
+ def variants(path)
271
+ return [] if path.nil?
272
+
273
+ expanded = File.expand_path(path.to_s)
274
+ [expanded, canonical(expanded)].uniq
275
+ end
276
+
277
+ def canonical(path)
278
+ File.realpath(path)
279
+ rescue SystemCallError
280
+ path
281
+ end
282
+ end
283
+ end
284
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+
5
+ module TypstRails
6
+ # Runs a Typst template through ERB in a given scope, for frameworks
7
+ # without an ActionView-style template handler (Sinatra, Rage).
8
+ #
9
+ # As in Rails `.typ` views, output from `<%= %>` is not escaped; use
10
+ # {Helpers#escape_typst} for untrusted values.
11
+ #
12
+ # @api private
13
+ module ErbSource
14
+ # Local names ERB can bind; other keys still reach typst_data.json.
15
+ LOCAL_NAME = /\A[a-z_][a-zA-Z0-9_]*\z/.freeze
16
+
17
+ # Defined at module level so the binding it returns closes over no
18
+ # locals of #render, which a same-named template local could clobber.
19
+ BLANK_BINDING = proc { binding }
20
+ private_constant :BLANK_BINDING
21
+
22
+ # @param source [String] template source
23
+ # @param scope [Object] self for the template: its instance variables
24
+ # and methods are visible to ERB
25
+ # @param locals [Hash] exposed to ERB as local variables
26
+ # @return [String] the evaluated Typst source
27
+ def self.render(source, scope, locals = {})
28
+ context = scope.instance_exec(&BLANK_BINDING)
29
+ locals.each do |name, value|
30
+ name = name.to_s
31
+ context.local_variable_set(name, value) if LOCAL_NAME.match?(name)
32
+ end
33
+ ::ERB.new(source, trim_mode: "-").result(context)
34
+ end
35
+ end
36
+ end