logifos 0.1.1-x86_64-darwin

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 284045ac9072efa74c49bc9d72ea5b90e6ef089caccb67470f7c9688a4fb3523
4
+ data.tar.gz: 784c6ee70f8e556765fdc3f87c75f5757cd500221b0cd8a8005ef2b8bd83dcfe
5
+ SHA512:
6
+ metadata.gz: 12f474919f808ae49d8831751f1326aa70aa27ec80079df40e4ac879d7e1662395867e6ff4a776c44dd6614ea07a704c43895bec16034902c89517b26ee3a421
7
+ data.tar.gz: 5f551794fabb701ebd2e5d34de326909dcc1541a8bb9a3913e8ae99087002c7616c2b260b884c3eaacc27b4f461931aa73d64af4ae3c36d0db7944a104f17b4e
data/HISTORY.txt ADDED
@@ -0,0 +1,33 @@
1
+ == Logifos 0.1.0
2
+
3
+ First release: Ruby connects to the bundled logifos engine.
4
+
5
+ * Platform gems carry the engine in two tiers: the MRI extension
6
+ (lib/logifos/<ruby version>/logifos_native), bound through magnus, and the
7
+ portable engine cdylib (lib/logifos/native/), which the ffi tier loads when
8
+ the extension is absent (TruffleRuby, an MRI whose extension did not build).
9
+ A source gem install compiles the extension.
10
+ * `Logifos::NativeRuntime.new` picks the extension when it loaded and the cdylib
11
+ otherwise, with no setup. `library_path:` still selects an external engine,
12
+ and `LOGIFOS_FFI_LIB` names a cdylib for the ffi tier.
13
+ * Each runtime binds its own library context and checks ABI 1, schema 1 and the
14
+ buffer/JSON feature bits before requests. Responses are copied by their exact
15
+ lengths and freed once through the library that allocated them.
16
+ * `negotiate` reports the implemented operations. A MathML `parse` request
17
+ returns the wire model and the Formula contract; `render` returns the SVG
18
+ document for a model rendered with the fonts of the call.
19
+ `render_mathml` parses a MathML document and renders it under the contract
20
+ the parse returned.
21
+ * Fonts are caller-side and belong to each call: `Logifos::NativeRuntime.font`
22
+ encodes caller-owned bytes for `options: { fallback_order:, fonts: }`. The
23
+ wrapper reads no host fonts and keeps no font state.
24
+ * Core refusals raise `Logifos::EngineError` with `code`, `path` and `stage`.
25
+ Loading, compatibility, transport and protocol failures raise
26
+ `LibraryError`, `CompatibilityError`, `TransportError` and `ProtocolError`.
27
+ * The MRI extension is declared Ractor-safe: a request is bytes in, bytes out
28
+ through per-call owned buffers, and the engine keeps no mutable global state.
29
+ * The release train builds every platform gem with both tiers, asserts that
30
+ they ride the gem, and installs and exercises the gem on six platforms before
31
+ publishing.
32
+
33
+ No migrations exist: no earlier version was released.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ribose Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # logifos-ruby
2
+
3
+ logifos-ruby connects Ruby to the bundled logifos Rust engine. Native
4
+ transport, negotiation, MathML parsing and SVG rendering with the fonts of
5
+ each call work through it; PNG output remains unavailable.
6
+
7
+ ## Bundled engine
8
+
9
+ The engine ships the way parsanol-ruby's does, in two tiers. Platform gems
10
+ carry the MRI extension (`lib/logifos/<ruby version>/logifos_native`), which
11
+ binds the engine through magnus and hands Ruby the response bytes directly,
12
+ and the portable engine cdylib (`lib/logifos/native/liblogifos`), which the
13
+ ffi-gem tier loads when the extension is absent (TruffleRuby, an MRI whose
14
+ extension did not build). The source gem compiles the extension on install.
15
+ `Logifos::NativeRuntime.new` picks the extension when it loaded and the cdylib
16
+ otherwise, so a plain install works with no setup:
17
+
18
+ ```ruby
19
+ require "logifos"
20
+
21
+ runtime = Logifos::NativeRuntime.new
22
+ capabilities = runtime.negotiate
23
+ puts capabilities.fetch("implemented_operations")
24
+ puts runtime.library.engine_version
25
+ ```
26
+
27
+ The extension is declared Ractor-safe: a request hands Ruby its response
28
+ bytes and retains nothing between calls.
29
+
30
+ Fonts stay caller-side: pass the OpenType MATH faces per call
31
+ (`options: { fallback_order:, fonts: }`). Building the source gem (the ruby
32
+ platform) requires Rust — rustc at least the engine's MSRV — and the `rb_sys`
33
+ gem, which the gem declares as a dependency; a prebuilt Rust toolchain is not
34
+ needed for platform gems. `LOGIFOS_FFI_LIB` names a cdylib for the ffi tier
35
+ explicitly.
36
+
37
+ `library_path:` still selects an external engine explicitly (absolute path to a
38
+ readable library). Each runtime binds its own library context and checks ABI 1,
39
+ schema 1, and the buffer/JSON feature bits before requests. Unknown feature
40
+ bits are ignored. The package version is independent of these wire versions.
41
+ Set `required_features:` to demand additional feature bits, such as
42
+ `Logifos::NativeRuntime::RENDER`.
43
+
44
+ `runtime.request(hash)` serializes an explicit wire request;
45
+ `runtime.request_bytes(string)` sends exactly the supplied JSON bytes, including
46
+ embedded NULs and invalid UTF-8, for core validation. Both return the response's
47
+ `result` hash on success. Responses are copied using their exact lengths and
48
+ freed once through the library that allocated them, before Ruby decodes JSON.
49
+ No native buffer escapes to the caller.
50
+
51
+ ## Rendering and per-call fonts
52
+
53
+ `runtime.render(formula, formula_contract:, format: :svg, options: {})` sends a
54
+ render request to the same core and returns the result hash, which holds the
55
+ `svg` document. The contract identity must come from a parse the caller made
56
+ or from the caller's pinned Formula schema; the wrapper does not invent one. A
57
+ render without fonts refuses typed with `MISSING_FONT` at `/options/fonts`, and
58
+ PNG refuses with `UNSUPPORTED_OUTPUT`.
59
+
60
+ `runtime.render_mathml(mathml, fonts:, format: :svg, options: {})` parses a
61
+ MathML document and renders the model under the contract the parse returned,
62
+ so the model and the contract always agree. Invalid MathML raises
63
+ `Logifos::EngineError` (`INVALID_SOURCE`; `TRANSFORM_FAILED` when the syntax
64
+ parses but does not transform):
65
+
66
+ ```ruby
67
+ fonts = [Logifos::NativeRuntime.font(id: "stix", bytes: File.binread(font_path))]
68
+ result = runtime.render_mathml("<math><mi>x</mi></math>", fonts: fonts)
69
+ puts result.fetch("svg")
70
+ ```
71
+
72
+ `Logifos.render` accepts the render arguments plus `library_path:` for an
73
+ external engine. Retain a `NativeRuntime` for repeated calls.
74
+
75
+ Fonts and options belong to each call. To encode caller-owned bytes:
76
+
77
+ ```ruby
78
+ font = Logifos::NativeRuntime.font(id: "Primary", bytes: supplied_bytes, face_index: 0)
79
+ options = { fonts: [font], fallback_order: ["Primary"], font_size_px: 18 }
80
+ ```
81
+
82
+ The helper computes SHA-256 and canonical base64 without validating font data;
83
+ the core reads each font when it renders and refuses typed when it cannot
84
+ (`INVALID_FONT`, `FONT_HASH_MISMATCH`) or when no font in the fallback order
85
+ carries a glyph the formula needs (`MISSING_GLYPH`). Pass the options to
86
+ `render(..., options: options)` or another wire request. No host fonts,
87
+ resource paths, global font mutation or implicit defaults are used by the
88
+ wrapper. Caller options are serialized without mutation and do not affect
89
+ later calls.
90
+
91
+ Core refusals raise `Logifos::EngineError`, preserving `code`, `path`, `stage`
92
+ and the diagnostic message. Library loading raises `LibraryError`; version or
93
+ feature mismatches raise `CompatibilityError`. Transport failures raise
94
+ `TransportError` with numeric `status` and symbolic `code`. Malformed response
95
+ envelopes raise `ProtocolError`. These all inherit from `Logifos::Error` and can
96
+ be rescued normally. Diagnostic messages are not stable API strings.
97
+
98
+ ## Development and focused checks
99
+
100
+ ```sh
101
+ bundle install
102
+ bundle exec rake compile
103
+ bundle exec rspec spec/render_spec.rb spec/logifos
104
+ bundle exec rubocop
105
+ ```
106
+
107
+ `bundle exec rake compile` builds the MRI extension for the running Ruby and
108
+ needs a Rust toolchain. Set `LOGIFOS_LIBRARY_PATH` to the absolute path of a
109
+ matching native library to run the native cases, and `LOGIFOS_FONT` to an
110
+ OpenType MATH face for the end-to-end MathML render. Without them, those cases
111
+ are explicitly skipped and the unit checks still run. The native cases cover
112
+ negotiation, UTF-8 byte limits, binary font transport, bad input, typed
113
+ refusals, independent contexts and repeated allocation/free.
114
+
115
+ `spec/package_smoke_spec.rb` builds the source gem, installs it into temporary
116
+ storage and compiles the extension there, so it needs a Rust toolchain and is
117
+ left to continuous integration.
118
+
119
+ Bundler creates a local `Gemfile.lock`; it is not committed.
120
+
121
+ ## Releases and migrations
122
+
123
+ 0.1.0 is the first release; its changes are recorded in [HISTORY.txt](HISTORY.txt).
124
+ Platform gems come only from the cross-gem train (`gem-build.yml` on push and
125
+ `release.yml` by dispatch), which asserts that both engine tiers ride every
126
+ platform gem and installs the gem on six platforms before publishing. There
127
+ are no migrations: no earlier version was released.
128
+
129
+ ## License
130
+
131
+ MIT; see [LICENSE.txt](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+
5
+ begin
6
+ require "rspec/core/rake_task"
7
+ rescue LoadError
8
+ # RSpec not available in this environment
9
+ end
10
+
11
+ require "rdoc/task"
12
+ require "rubygems/package_task"
13
+
14
+ begin
15
+ require "opal/rspec/rake_task"
16
+ rescue LoadError, NoMethodError
17
+ # Opal not available or incompatible with current Ruby version
18
+ end
19
+
20
+ GEMSPEC = Gem::Specification.load("logifos.gemspec")
21
+
22
+ # Load rake tasks from rakelib/
23
+ Dir.glob("rakelib/*.rake").each { |r| load r }
24
+
25
+ desc "Run all tests"
26
+ RSpec::Core::RakeTask.new(:spec)
27
+
28
+ namespace :spec do
29
+ desc "Run unit tests only"
30
+ RSpec::Core::RakeTask.new(:unit) do |task|
31
+ task.pattern = "spec/logifos/**/*_spec.rb"
32
+ end
33
+
34
+ if defined?(Opal::RSpec::RakeTask)
35
+ desc "Run Opal (JavaScript) tests"
36
+ Opal::RSpec::RakeTask.new(:opal) do |task|
37
+ task.append_path "lib"
38
+ end
39
+ end
40
+ end
41
+
42
+ RDoc::Task.new do |rdoc|
43
+ rdoc.rdoc_dir = "rdoc"
44
+ rdoc.title = "Logifos"
45
+ rdoc.options << "--line-numbers"
46
+ rdoc.rdoc_files.include("README.adoc")
47
+ rdoc.rdoc_files.include("lib/**/*.rb")
48
+ end
49
+
50
+ desc "Print LOC statistics"
51
+ task :stat do
52
+ %w[lib spec example].each do |dir|
53
+ next unless Dir.exist?(dir)
54
+
55
+ loc = `find #{dir} -name "*.rb" | xargs wc -l | grep 'total'`.split.first.to_i
56
+ printf("%<dir>20s %<loc>d\n", dir: dir, loc: loc)
57
+ end
58
+ end
59
+
60
+ # ===== Native Gem Building =====
61
+ namespace :gem do
62
+ desc "Build source gem (compile on install)"
63
+ task "native:any" do
64
+ sh "rake gem:platform:any gem"
65
+ end
66
+
67
+ # Vendor the pure-portable cdylib into PLATFORM gems (TODO.perf/9):
68
+ # the ruby (source) gem stays binary-free; each cross-gem carries its
69
+ # own triple's liblogifos next to the extension for the ffi tier
70
+ # (MRI resilience fallback, TruffleRuby native).
71
+ desc "Build ext/logifos_cdylib for the active cross target and vendor it"
72
+ task "vendor_cdylib" do
73
+ triplet = ENV["CARGO_BUILD_TARGET"] || ENV.fetch("RUST_TARGET", nil)
74
+ args = ["cargo", "build", "--release", "-p", "logifos_cdylib"]
75
+ args += ["--target", triplet] if triplet
76
+ sh(*args)
77
+ dir = triplet ? "target/#{triplet}/release" : "target/release"
78
+ name = %w[liblogifos.so liblogifos.dylib logifos.dll]
79
+ .map { |n| File.join(dir, n) }
80
+ .find { |f| File.file?(f) }
81
+ raise "cdylib not found under #{dir}" unless name
82
+
83
+ cp name, "lib/logifos/native/"
84
+ end
85
+
86
+ desc "Define the gem task to build on any platform (compile on install)"
87
+ task "platform:any" do
88
+ spec = Gem::Specification.load("logifos.gemspec").dup
89
+ task = Gem::PackageTask.new(spec)
90
+ task.define
91
+ end
92
+ end
93
+
94
+ task default: :spec
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logifos
4
+ # Base for recoverable runtime failures.
5
+ class Error < StandardError; end
6
+
7
+ # The explicitly requested library could not be loaded.
8
+ class LibraryError < Error; end
9
+
10
+ # The library does not support the required wire versions or features.
11
+ class CompatibilityError < LibraryError; end
12
+
13
+ # A library returned an invalid response envelope.
14
+ class ProtocolError < Error; end
15
+
16
+ # A native call failed before producing a JSON response.
17
+ class TransportError < Error
18
+ CODES = { 1 => "INVALID_REQUEST", 2 => "ALLOCATION_FAILED", 3 => "INTERNAL_ERROR" }.freeze
19
+
20
+ attr_reader :status, :code
21
+
22
+ def initialize(status)
23
+ @status = status
24
+ @code = CODES.fetch(status, "UNKNOWN_TRANSPORT_STATUS")
25
+ super("native transport failed: #{@code} (#{status})")
26
+ end
27
+ end
28
+
29
+ # A typed refusal returned by the core; diagnostic text is not a stable API.
30
+ class EngineError < Error
31
+ attr_reader :code, :path, :stage
32
+
33
+ def initialize(code:, message:, path:, stage:)
34
+ @code = code
35
+ @path = path
36
+ @stage = stage
37
+ super(message)
38
+ end
39
+ end
40
+ end
Binary file
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logifos
4
+ # The MRI tier: the platform gem's compiled extension defines the
5
+ # transport queries and `request_v1` below through magnus (logifos-rs's
6
+ # logifos-ffi `ruby` feature); this Ruby module only reports availability
7
+ # and triggers the lazy load. The ffi-gem cdylib tier (NativeLibrary)
8
+ # serves when the extension is absent.
9
+ module Native
10
+ @native_state = :pending
11
+
12
+ class << self
13
+ # First call performs the lazy bundle load: binding the statically
14
+ # linked engine costs on startup, and `require "logifos"` must stay
15
+ # cheap for consumers that only configure up front.
16
+ def available?
17
+ native_load!
18
+ extension_loaded?
19
+ end
20
+
21
+ def extension_loaded?
22
+ native_load! == :loaded
23
+ end
24
+
25
+ private
26
+
27
+ def native_load!
28
+ return @native_state unless @native_state == :pending
29
+
30
+ @native_state = load_extension
31
+ end
32
+
33
+ # rake-compiler installs the extension under the running Ruby's
34
+ # version directory; a source install puts it on the load path flat.
35
+ def load_extension
36
+ require "logifos/#{RUBY_VERSION.split(".").take(2).join(".")}/logifos_native"
37
+ :loaded
38
+ rescue LoadError
39
+ begin
40
+ require "logifos/logifos_native"
41
+ :loaded
42
+ rescue LoadError
43
+ :unavailable
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+ require_relative "errors"
5
+
6
+ module Logifos
7
+ # The ABI's owned, length-delimited response. Only its allocator may free it.
8
+ class NativeBuffer < FFI::Struct
9
+ layout :ptr, :pointer, :len, :size_t
10
+ end
11
+
12
+ # One loaded engine serves a runtime: the MRI extension's Logifos::Native
13
+ # when the platform gem or a source install compiled it (no library_path),
14
+ # else the ffi-gem cdylib tier bound by path. Each tier owns the allocation
15
+ # and free function for its calls.
16
+ class NativeLibrary
17
+ QUERY_TYPES = { abi_version: :uint32, schema_version: :uint32, features: :uint64, engine_version: :string }.freeze
18
+ # The transport's refusal of its arguments; the extension tier reports
19
+ # it as a nil response.
20
+ INVALID_REQUEST = 1
21
+ VENDORED = %w[liblogifos.dylib liblogifos.so logifos.dll].freeze
22
+
23
+ attr_reader :library_path, :abi_version, :schema_version, :engine_version, :features
24
+
25
+ # An explicit library_path must name a readable library by absolute path;
26
+ # a located one is this gem's own search result and is trusted.
27
+ def initialize(required_features:, library_path: nil, located: false)
28
+ @library_path = library_path&.dup&.freeze
29
+ validate_path(library_path) if library_path && !located
30
+ @api = bind_library if library_path
31
+ @abi_version, @schema_version, @engine_version, @features = queries
32
+ check_compatibility(required_features)
33
+ rescue LoadError, FFI::NotFoundError => e
34
+ raise LibraryError, "cannot load requested native library: #{e.message}"
35
+ end
36
+
37
+ # Search order: explicit override, gem-vendored cdylib next to the gem's
38
+ # lib (lib/logifos/native, where the cross-gem build puts it), then the
39
+ # system linker path — the parsanol-ruby ffi tier's order.
40
+ def self.locate_library(lib = File.expand_path("..", __dir__))
41
+ candidates(lib).find { |candidate| File.file?(candidate) || loadable?(candidate) }
42
+ end
43
+
44
+ def self.candidates(lib)
45
+ override = ENV.fetch("LOGIFOS_FFI_LIB", nil)
46
+ override = nil if override && override.empty?
47
+ vendored = VENDORED.filter_map do |name|
48
+ path = File.expand_path(name, File.join(lib, "logifos", "native"))
49
+ path if File.file?(path)
50
+ end
51
+ [override, *vendored, "logifos"].compact
52
+ end
53
+
54
+ def self.loadable?(candidate)
55
+ FFI::DynamicLibrary.open(candidate, FFI::DynamicLibrary::RTLD_NOW)
56
+ true
57
+ rescue LoadError, StandardError
58
+ false
59
+ end
60
+
61
+ def exchange(bytes)
62
+ raise ArgumentError, "request bytes must be a String" unless bytes.is_a?(String)
63
+
64
+ bytes = bytes.b
65
+ input = nil
66
+ return request_through_extension(bytes) unless @api
67
+
68
+ input = FFI::MemoryPointer.new(:uint8, [bytes.bytesize, 1].max)
69
+ input.put_bytes(0, bytes)
70
+ exchange_buffer(input, bytes.bytesize)
71
+ ensure
72
+ input&.free
73
+ end
74
+
75
+ private
76
+
77
+ def queries
78
+ if @api
79
+ [@api.logifos_abi_version, @api.logifos_schema_version, @api.logifos_engine_version.dup.freeze,
80
+ @api.logifos_features]
81
+ else
82
+ [Native.abi_version, Native.schema_version, Native.engine_version.dup.freeze, Native.features]
83
+ end
84
+ end
85
+
86
+ def request_through_extension(bytes)
87
+ response = Native.request_v1(bytes)
88
+ raise TransportError, INVALID_REQUEST unless response
89
+
90
+ response.dup.force_encoding(Encoding::UTF_8)
91
+ end
92
+
93
+ def validate_path(path)
94
+ return if path.is_a?(String) && File.absolute_path(path) == path && File.file?(path) && File.readable?(path)
95
+
96
+ raise LibraryError, "library_path must name a readable library by absolute path"
97
+ end
98
+
99
+ def bind_library
100
+ path = library_path
101
+ Module.new do
102
+ extend FFI::Library
103
+
104
+ ffi_lib path
105
+ QUERY_TYPES.each do |name, type|
106
+ attach_function :"logifos_#{name}", [], type
107
+ end
108
+ attach_function :logifos_request_v1, %i[pointer size_t pointer], :uint32
109
+ attach_function :logifos_buffer_free_v1, [NativeBuffer.by_value], :void
110
+ end
111
+ end
112
+
113
+ def check_compatibility(required)
114
+ raise CompatibilityError, "unsupported ABI version: #{abi_version}" unless abi_version == 1
115
+ raise CompatibilityError, "unsupported schema version: #{schema_version}" unless schema_version == 1
116
+ return if features & required == required
117
+
118
+ raise CompatibilityError, "native library lacks required features: #{required}"
119
+ end
120
+
121
+ def release(buffer)
122
+ @api.logifos_buffer_free_v1(buffer)
123
+ buffer[:ptr] = FFI::Pointer::NULL
124
+ buffer[:len] = 0
125
+ end
126
+
127
+ def exchange_buffer(input, length)
128
+ buffer = NativeBuffer.new
129
+ begin
130
+ status = @api.logifos_request_v1(input, length, buffer)
131
+ raise TransportError, status unless status.zero?
132
+ raise ProtocolError, "native library returned a null response" if buffer[:ptr].null?
133
+
134
+ buffer[:ptr].read_string(buffer[:len]).force_encoding(Encoding::UTF_8)
135
+ ensure
136
+ release(buffer)
137
+ end
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require_relative "native_library"
6
+ require_relative "response"
7
+
8
+ module Logifos
9
+ # A per-library context for the versioned JSON facade; it owns no font state.
10
+ class NativeRuntime
11
+ BUFFER_V1 = 1
12
+ JSON_V1 = 2
13
+ RENDER = 4
14
+
15
+ attr_reader :library
16
+
17
+ # The gem ships the engine two ways, as parsanol-ruby does: platform
18
+ # gems carry the MRI extension (lib/logifos/<ruby version>/) and the
19
+ # portable cdylib (lib/logifos/native/) for the ffi tier; a source-gem
20
+ # install compiles the extension. library_path keeps working for an
21
+ # external engine.
22
+ def self.bundled_library_path(lib: File.expand_path("..", __dir__))
23
+ NativeLibrary.locate_library(lib) or raise LibraryError, "no bundled engine library in this gem"
24
+ end
25
+
26
+ # library_path selects an external engine explicitly; otherwise the MRI
27
+ # extension serves when it loaded, else the vendored cdylib.
28
+ def initialize(library_path: nil, required_features: BUFFER_V1 | JSON_V1)
29
+ required = required_features | BUFFER_V1 | JSON_V1
30
+ @library = if library_path
31
+ NativeLibrary.new(library_path: library_path, required_features: required)
32
+ elsif Native.available?
33
+ NativeLibrary.new(required_features: required)
34
+ else
35
+ bundled = NativeRuntime.bundled_library_path
36
+ NativeLibrary.new(library_path: bundled, required_features: required, located: true)
37
+ end
38
+ end
39
+
40
+ def request(message)
41
+ request_bytes(JSON.generate(message))
42
+ end
43
+
44
+ def request_bytes(bytes)
45
+ Response.decode(library.exchange(bytes))
46
+ end
47
+
48
+ def negotiate(options: {})
49
+ request(envelope("negotiate", options))
50
+ end
51
+
52
+ def render(formula_model, formula_contract:, format: :svg, options: {})
53
+ request(envelope("render", options).merge(
54
+ formula: formula_model, formula_contract: formula_contract, output: format.to_s
55
+ ))
56
+ end
57
+
58
+ # Renders a MathML source document end to end: the engine parses it into
59
+ # its wire model, then renders that model with the caller's fonts. The
60
+ # contract returned by the parse — the engine's own — is the contract the
61
+ # render asserts, so caller and artifact always agree.
62
+ def render_mathml(mathml, fonts:, format: :svg, options: {})
63
+ parsed = request(parse_envelope(mathml))
64
+ render(
65
+ parsed.fetch("model"),
66
+ formula_contract: parsed.fetch("formula_contract"),
67
+ format: format,
68
+ options: render_options(options, fonts)
69
+ )
70
+ end
71
+
72
+ # Encodes supplied bytes without loading a font or asserting its validity.
73
+ def self.font(id:, bytes:, face_index: 0)
74
+ raise ArgumentError, "font bytes must be a String" unless bytes.is_a?(String)
75
+
76
+ bytes = bytes.b
77
+ { id: id, sha256: Digest::SHA256.hexdigest(bytes), bytes_base64: [bytes].pack("m0"), face_index: face_index }
78
+ end
79
+
80
+ private
81
+
82
+ def parse_envelope(mathml)
83
+ envelope("parse", {}).merge(format: "mathml", source: mathml.to_s)
84
+ end
85
+
86
+ def render_options(options, fonts)
87
+ order = options.fetch(:fallback_order) { fonts.map { |font| font[:id] } }
88
+ options.merge(fonts: fonts, fallback_order: order)
89
+ end
90
+
91
+ def envelope(operation, options)
92
+ { abi_version: 1, schema_version: 1, op: operation, options: options }
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "errors"
5
+
6
+ module Logifos
7
+ # Checks the wire envelope before exposing a result or typed core refusal.
8
+ module Response
9
+ def self.decode(bytes)
10
+ raise ProtocolError, "native response is not UTF-8" unless bytes.valid_encoding?
11
+
12
+ envelope = JSON.parse(bytes)
13
+ validate_envelope(envelope)
14
+ return envelope.fetch("result") if envelope["ok"]
15
+
16
+ error = envelope.fetch("error")
17
+ raise EngineError.new(**error.transform_keys(&:to_sym))
18
+ rescue JSON::ParserError
19
+ raise ProtocolError, "native response is not valid JSON"
20
+ end
21
+
22
+ def self.validate_envelope(envelope)
23
+ validate_versions(envelope)
24
+ field = if envelope["ok"] == true && envelope["result"].is_a?(Hash)
25
+ "result"
26
+ elsif envelope["ok"] == false && valid_error?(envelope["error"])
27
+ "error"
28
+ end
29
+ return if field && envelope.keys.sort == ["abi_version", "schema_version", "ok", field].sort
30
+
31
+ raise ProtocolError, "native response has an invalid envelope"
32
+ end
33
+
34
+ def self.validate_versions(envelope)
35
+ return if envelope.is_a?(Hash) && envelope.values_at("abi_version", "schema_version").all? { |v| v.eql?(1) }
36
+
37
+ raise CompatibilityError, "native response has incompatible versions"
38
+ end
39
+
40
+ def self.valid_error?(error)
41
+ fields = %w[code message path stage]
42
+ error.is_a?(Hash) && error.keys.sort == fields && error.values.all?(String)
43
+ end
44
+ private_class_method :validate_envelope, :validate_versions, :valid_error?
45
+ end
46
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logifos
4
+ VERSION = "0.1.1"
5
+ end
data/lib/logifos.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "logifos/version"
4
+ require_relative "logifos/errors"
5
+ require_relative "logifos/native"
6
+ require_relative "logifos/native_runtime"
7
+
8
+ # The bootstrap module documents its render boundary at the method.
9
+ module Logifos
10
+ # Renders through the bundled engine; library_path still selects an
11
+ # external engine explicitly.
12
+ def self.render(formula_model, formula_contract:, library_path: nil, format: :svg, options: {})
13
+ NativeRuntime.new(library_path: library_path).render(
14
+ formula_model, formula_contract: formula_contract, format: format, options: options
15
+ )
16
+ end
17
+ end
data/logifos.gemspec ADDED
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/logifos/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "logifos"
7
+ spec.version = Logifos::VERSION
8
+ spec.platform = Gem::Platform::RUBY
9
+
10
+ spec.authors = ["Ribose Inc."]
11
+ spec.email = ["open.source@ribose.com"]
12
+
13
+ spec.summary = "Math formula rendering through the bundled logifos engine."
14
+ spec.description = <<~DESC
15
+ Renders math formulas to deterministic SVG through the bundled
16
+ logifos Rust engine: platform gems ship the native extension and the
17
+ portable engine cdylib, syntax models transform into the central
18
+ Formula model, which lays out to a box tree and emits SVG. An external
19
+ engine can still be passed with library_path:.
20
+ DESC
21
+ spec.homepage = "https://github.com/logifos/logifos-ruby"
22
+ spec.license = "MIT"
23
+
24
+ spec.metadata = {
25
+ "bug_tracker_uri" => "https://github.com/logifos/logifos-ruby/issues",
26
+ "changelog_uri" => "https://github.com/logifos/logifos-ruby/blob/main/HISTORY.txt",
27
+ "homepage_uri" => "https://github.com/logifos/logifos-ruby",
28
+ "source_code_uri" => "https://github.com/logifos/logifos-ruby",
29
+ "rubygems_mfa_required" => "true"
30
+ }
31
+
32
+ # Rust extension
33
+ spec.extensions = ["ext/logifos_native/extconf.rb"]
34
+
35
+ spec.files = Dir.glob("{lib,ext}/**/*") + %w[
36
+ HISTORY.txt
37
+ LICENSE.txt
38
+ Rakefile
39
+ README.md
40
+ logifos.gemspec
41
+ Cargo.toml
42
+ Cargo.lock
43
+ ]
44
+ spec.files.reject! { |f| File.directory?(f) }
45
+ # Cargo build trees are never gem content (a dirty local
46
+ # ext/logifos_native/target once inflated a build to 218 MB).
47
+ spec.files.reject! { |f| f.include?("/target/") || f.start_with?("target/") }
48
+ # Binaries are never tracked in git, and the ruby (source) gem stays
49
+ # slim: the pure-portable cdylib is vendored ONLY into platform gems
50
+ # by the cross-gem build (rake gem:vendor_cdylib), never by a plain
51
+ # `gem build`.
52
+ spec.files.reject! do |f|
53
+ f =~ /\.(dll|so|dylib|lib|bundle)\Z/ &&
54
+ !(ENV["LOGIFOS_VENDOR_CDYLIB"] == "1" &&
55
+ f =~ %r{\Alib/logifos/native/liblogifos\.(so|dylib|dll)\Z})
56
+ end
57
+ spec.require_paths = ["lib"]
58
+
59
+ spec.required_ruby_version = ">= 3.2.0"
60
+
61
+ # Required for Rust extension
62
+ spec.add_dependency "rb_sys", "~> 0.9.39"
63
+ # The ffi tier (MRI without the extension, TruffleRuby) binds the
64
+ # vendored cdylib through these.
65
+ spec.add_dependency "ffi", "~> 1.17"
66
+ spec.add_dependency "json", "~> 2.6"
67
+ end
metadata ADDED
@@ -0,0 +1,101 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: logifos
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: x86_64-darwin
6
+ authors:
7
+ - Ribose Inc.
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ffi
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.6'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.6'
41
+ description: |
42
+ Renders math formulas to deterministic SVG through the bundled
43
+ logifos Rust engine: platform gems ship the native extension and the
44
+ portable engine cdylib, syntax models transform into the central
45
+ Formula model, which lays out to a box tree and emits SVG. An external
46
+ engine can still be passed with library_path:.
47
+ email:
48
+ - open.source@ribose.com
49
+ executables: []
50
+ extensions: []
51
+ extra_rdoc_files: []
52
+ files:
53
+ - HISTORY.txt
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - lib/logifos.rb
58
+ - lib/logifos/3.2/logifos_native.bundle
59
+ - lib/logifos/3.3/logifos_native.bundle
60
+ - lib/logifos/3.4/logifos_native.bundle
61
+ - lib/logifos/4.0/logifos_native.bundle
62
+ - lib/logifos/errors.rb
63
+ - lib/logifos/native.rb
64
+ - lib/logifos/native/liblogifos.dylib
65
+ - lib/logifos/native_library.rb
66
+ - lib/logifos/native_runtime.rb
67
+ - lib/logifos/response.rb
68
+ - lib/logifos/version.rb
69
+ - logifos.gemspec
70
+ homepage: https://github.com/logifos/logifos-ruby
71
+ licenses:
72
+ - MIT
73
+ metadata:
74
+ bug_tracker_uri: https://github.com/logifos/logifos-ruby/issues
75
+ changelog_uri: https://github.com/logifos/logifos-ruby/blob/main/HISTORY.txt
76
+ homepage_uri: https://github.com/logifos/logifos-ruby
77
+ source_code_uri: https://github.com/logifos/logifos-ruby
78
+ rubygems_mfa_required: 'true'
79
+ post_install_message:
80
+ rdoc_options: []
81
+ require_paths:
82
+ - lib
83
+ required_ruby_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '3.2'
88
+ - - "<"
89
+ - !ruby/object:Gem::Version
90
+ version: 4.1.dev
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubygems_version: 3.5.23
98
+ signing_key:
99
+ specification_version: 4
100
+ summary: Math formula rendering through the bundled logifos engine.
101
+ test_files: []