sigli 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 56da7d058e225327bcf83fd88263942ee05a13b8110d4014d47db1d8059231d8
4
+ data.tar.gz: 23f806cae5b3a308cdbc9594f1c18f8a059e179afe7c3ff1cc74d99be650893a
5
+ SHA512:
6
+ metadata.gz: c8cc7ccbd1433a77df65cceb7c0e6bcdeb9ef276554bdf7d5fe0a8f3fe19c21403035926bff4164f1921a8aa71f36af2af97ffaeee8352d678d1971950dd7072
7
+ data.tar.gz: 04be6ebed06c2383cf59c2f587100be5e188d2582097754f7271c3bd419c3ce60efd45ce6ccd47947f4f69eb00dd9e8ec3ee86ce378e85a88ca5d94b417fb39d
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RADIS Next Gen Technologies Pvt Ltd
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,244 @@
1
+ # Sigli Ruby SDK
2
+
3
+ Official Ruby client for the [Sigli](https://sigli.dev) document API: HTML/URL to PDF, screenshots, OCR,
4
+ PDF to Markdown, PDF tools, AI extraction, batch jobs, workflows and webhooks.
5
+
6
+ - Standard library only (`net/http`, `json`, `openssl`). No runtime dependencies.
7
+ - Ruby >= 3.0.
8
+ - Automatic retries with backoff, `Idempotency-Key` support, typed errors with request ids.
9
+
10
+ ## Install
11
+
12
+ <!-- install:begin -->
13
+ ```bash
14
+ gem install sigli
15
+ ```
16
+
17
+ Or in a Gemfile: `gem "sigli"`. To work from a checkout of this repo instead: `cd sdks/ruby && gem build sigli.gemspec && gem install ./sigli-0.1.0.gem`.
18
+ <!-- install:end -->
19
+
20
+ ## Quickstart
21
+
22
+ ```ruby
23
+ require "sigli"
24
+
25
+ client = Sigli::Client.new(api_key: ENV["SIGLI_API_KEY"])
26
+
27
+ pdf = client.html_to_pdf("<h1>Hello</h1>", format: "A4")
28
+ File.binwrite("hello.pdf", pdf)
29
+ ```
30
+
31
+ ## Configuration
32
+
33
+ | Option | Default | Notes |
34
+ |---------------|------------------------------------|-----------------------------------------------|
35
+ | `api_key:` | `ENV["SIGLI_API_KEY"]` | Sent as `X-API-Key`. Required. |
36
+ | `base_url:` | `ENV["SIGLI_BASE_URL"]` or `https://api.sigli.dev` | Use `http://localhost:5500` for local dev. |
37
+ | `timeout:` | `60` seconds | Per attempt; can be overridden per call. |
38
+ | `max_retries:`| `2` | Extra attempts after the first. |
39
+
40
+ Every method also accepts `timeout:` and, for writes, `idempotency_key:`. Methods that return files also accept
41
+ `output_path:`, which streams the response to disk and returns the path instead of the bytes.
42
+
43
+ Any other keyword argument is passed through unchanged as an API field, using the API's own names
44
+ (`format:`, `full_page:`, `dark_mode:`, `use_ai:`, `sandbox:`, ...).
45
+
46
+ ## API surface
47
+
48
+ | Area | Methods |
49
+ |------------|---------|
50
+ | Convert | `process(convert_type, body)`, `html_to_pdf`, `url_to_pdf`, `screenshot`, `ocr`, `pdf_to_markdown` |
51
+ | PDF tools | `client.pdf.merge`, `split`, `compress`, `rotate`, `watermark`, `protect`, `unlock`, `redact`, `page_numbers`, `remove_pages`, `reorder`, `metadata`, `info`, `forms_extract`, `forms_fill`, `to_images` |
52
+ | AI | `client.ai.summary`, `structured`, `translate`, `query` |
53
+ | Batch | `client.batch.submit`, `get`, `list`, `wait` (also `client.wait_for_batch`) |
54
+ | Workflows | `client.workflows.list`, `get`, `create`, `run`, `runs` |
55
+ | Webhooks | `client.webhooks.list`, `create`, `delete`, `Sigli.verify_webhook_signature` |
56
+ | Anything else | `client.request(method, path, body:, query:, headers:)` returns the raw envelope |
57
+
58
+ `process` and the convert helpers return bytes (a binary `String`) when the API returns a file, and the response's
59
+ `data` hash when it returns JSON (for example with `return_url: true`, a `webhook`, or an async `202` job).
60
+
61
+ ## File inputs
62
+
63
+ Anywhere a document is expected you can pass:
64
+
65
+ | Input | Sent as |
66
+ |----------------------------------------|----------------|
67
+ | Binary `String` (`File.binread`, `.b`) | `file_base64` |
68
+ | `Pathname`, an `IO`/`File`, or a path `String` | `file_base64` (read locally) |
69
+ | `"https://..."` / `"http://..."` | `file_url` (Sigli fetches it) |
70
+
71
+ A plain UTF-8 string that is not a URL is treated as a path. If that path does not exist you get
72
+ `Sigli::Error` with code `invalid_argument`.
73
+
74
+ ## Errors
75
+
76
+ All failures raise `Sigli::Error`:
77
+
78
+ ```ruby
79
+ begin
80
+ client.pdf.info("contract.pdf")
81
+ rescue Sigli::Error => e
82
+ e.status # HTTP status, 0 for network/timeout/client-side errors
83
+ e.code # "bad_request", "plan_upgrade_required", "quota_exceeded", "timeout", ...
84
+ e.message # server message
85
+ e.request_id # x-request-id header; quote it to support
86
+ end
87
+ ```
88
+
89
+ `Sigli::ConnectionError` (a subclass) is raised for network failures (`network_error`) and timeouts (`timeout`).
90
+ A `402 plan_upgrade_required` means your plan does not include that feature (batch, webhooks and AI are paid
91
+ features).
92
+
93
+ ## Retries and idempotency
94
+
95
+ - Retried: HTTP 429, 502, 503, 504 and network errors/timeouts, with exponential backoff plus jitter (0.5s, 1s,
96
+ 2s, ... capped at 8s). A `Retry-After` header is honored (capped at 60s).
97
+ - Not retried: `429 quota_exceeded` (your monthly pool will not refill by waiting) and `503 feature_unavailable`.
98
+ - `GET`/`DELETE` are retried freely. `POST` is retried **only** when you pass `idempotency_key:`. The server
99
+ replays the stored response for a repeated key, so a retry never double-charges credits.
100
+
101
+ ```ruby
102
+ client.html_to_pdf(html, idempotency_key: "invoice-1042-v1")
103
+ ```
104
+
105
+ Keys must be 1-128 characters.
106
+
107
+ ## Examples
108
+
109
+ ### 1. Invoice PDF generation
110
+
111
+ ```ruby
112
+ require "sigli"
113
+ require "erb"
114
+
115
+ client = Sigli::Client.new
116
+
117
+ template = ERB.new(<<~HTML)
118
+ <html><body style="font-family: sans-serif">
119
+ <h1>Invoice <%= invoice[:number] %></h1>
120
+ <p>Bill to: <%= ERB::Util.h(invoice[:customer]) %></p>
121
+ <table>
122
+ <% invoice[:lines].each do |l| %>
123
+ <tr><td><%= ERB::Util.h(l[:item]) %></td><td><%= format("%.2f", l[:amount]) %></td></tr>
124
+ <% end %>
125
+ </table>
126
+ <p><strong>Total: <%= format("%.2f", invoice[:lines].sum { |l| l[:amount] }) %></strong></p>
127
+ </body></html>
128
+ HTML
129
+
130
+ invoice = { number: "INV-1042", customer: "Acme Ltd",
131
+ lines: [{ item: "API credits", amount: 99.0 }, { item: "Support", amount: 20.0 }] }
132
+
133
+ client.html_to_pdf(template.result(binding),
134
+ format: "A4",
135
+ output_path: "INV-1042.pdf",
136
+ # Same invoice, same key: retries and re-runs never bill twice.
137
+ idempotency_key: "invoice-#{invoice[:number]}")
138
+ ```
139
+
140
+ ### 2. Scanned-receipt OCR
141
+
142
+ ```ruby
143
+ client = Sigli::Client.new
144
+
145
+ result = client.ocr(Pathname("receipts/2026-10-25-cafe.jpg"))
146
+ puts result["text"]
147
+
148
+ total = result["text"][/total\s*[:$]?\s*([\d.,]+)/i, 1]
149
+ puts "Receipt total: #{total}"
150
+ ```
151
+
152
+ Large scans may be processed asynchronously: if `result["status"] == "queued"`, poll
153
+ `client.request("GET", "/jobs/#{result["job_id"]}")` until it reports `completed`.
154
+
155
+ ### 3. Batch of 500 URLs with `wait_for_batch`
156
+
157
+ ```ruby
158
+ client = Sigli::Client.new
159
+ urls = File.readlines("urls.txt", chomp: true).reject(&:empty?)
160
+
161
+ urls.each_slice(Sigli::Batch::MAX_ITEMS).with_index do |chunk, i|
162
+ batch = client.batch.submit(
163
+ chunk.map { |u| { source_url: u } },
164
+ convert_type: "url-to-pdf",
165
+ idempotency_key: "nightly-archive-2026-10-25-#{i}"
166
+ )
167
+ done = client.wait_for_batch(batch["batch_id"], poll_interval: 2, timeout: 1800)
168
+ failed = done["results"].select { |r| r["status"] == "failed" }
169
+ puts "batch #{done['batch_id']}: #{done['status']}, #{failed.size} failed"
170
+ end
171
+ ```
172
+
173
+ ### 4. Webhook verification in an HTTP handler (Rack / Sinatra)
174
+
175
+ Verify against the **raw** request body. Parsing and re-serializing the JSON changes the bytes and the signature
176
+ will not match.
177
+
178
+ ```ruby
179
+ require "sinatra"
180
+ require "json"
181
+ require "sigli"
182
+
183
+ SECRET = ENV.fetch("SIGLI_WEBHOOK_SECRET") # returned once by client.webhooks.create
184
+
185
+ post "/hooks/sigli" do
186
+ raw = request.body.read
187
+ halt 401 unless Sigli.verify_webhook_signature(raw, request.env["HTTP_X_SIGLI_SIGNATURE"], SECRET)
188
+
189
+ event = JSON.parse(raw)
190
+ case request.env["HTTP_X_SIGLI_EVENT"]
191
+ when "batch.completed"
192
+ BatchFinishedJob.perform_later(event["data"]["batch_id"])
193
+ end
194
+ status 204
195
+ end
196
+ ```
197
+
198
+ Plain Rack works the same way with `env["rack.input"].read`. Note: only webhooks registered via
199
+ `client.webhooks.create` are signed. One-off URLs passed as `webhook`/`webhook_url` on a request are
200
+ delivered without a signature, so do not rely on them for anything you need to trust.
201
+
202
+ ### 5. Merging and watermarking contracts
203
+
204
+ ```ruby
205
+ client = Sigli::Client.new
206
+
207
+ merged = client.pdf.merge([
208
+ "contracts/master-services-agreement.pdf",
209
+ Pathname("contracts/schedule-a-pricing.pdf"),
210
+ "https://files.example.com/contracts/dpa.pdf" # URLs must come after local files
211
+ ])
212
+
213
+ client.pdf.watermark(merged,
214
+ text: "CONFIDENTIAL - ACME LTD",
215
+ opacity: 0.15,
216
+ position: "center",
217
+ output_path: "acme-contract-pack.pdf")
218
+ ```
219
+
220
+ ### 6. AI structured extraction from an invoice
221
+
222
+ ```ruby
223
+ client = Sigli::Client.new(timeout: 120)
224
+
225
+ data = client.ai.structured("invoices/vendor-7731.pdf",
226
+ fields: %w[invoice_number invoice_date vendor_name total_amount currency])
227
+
228
+ fields = data["fields"] || {}
229
+ puts "#{fields['vendor_name']} #{fields['invoice_number']}: #{fields['total_amount']} #{fields['currency']}"
230
+ data["tables"]&.each { |row| p row }
231
+ ```
232
+
233
+ If the model's output could not be parsed as JSON, the response is `{"raw" => "..."}` instead.
234
+
235
+ ## Development
236
+
237
+ ```bash
238
+ cd sdks/ruby
239
+ rake test # unit tests, local mock server, no network
240
+ SIGLI_API_KEY=... SIGLI_BASE_URL=http://localhost:5500 rake test # also runs the live smoke tests
241
+ ```
242
+
243
+ The integration tests read sample files from `../../.qa-corpus` (override with `SIGLI_QA_CORPUS`) and are skipped
244
+ unless both `SIGLI_API_KEY` and `SIGLI_BASE_URL` are set.
data/lib/sigli/ai.rb ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class AI
5
+ def initialize(client)
6
+ @client = client
7
+ end
8
+
9
+ def summary(file, instructions: nil, **opts)
10
+ run("summary", file, { "instructions" => instructions }, **opts)
11
+ end
12
+
13
+ def structured(file, fields: nil, **opts)
14
+ run("structured", file, { "fields" => fields }, **opts)
15
+ end
16
+
17
+ def translate(file, target_language, **opts)
18
+ run("translate", file, { "target_language" => target_language }, **opts)
19
+ end
20
+
21
+ def query(file, query, **opts)
22
+ run("query", file, { "query" => query }, **opts)
23
+ end
24
+
25
+ private
26
+
27
+ def run(name, file, extra, idempotency_key: nil, timeout: nil, **params)
28
+ body = Files.apply(params.transform_keys(&:to_s).merge(extra.compact), file)
29
+ @client.call("POST", "/v1/extract/#{name}", body: body, idempotency_key: idempotency_key, timeout: timeout)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class Audit
5
+ def initialize(client)
6
+ @client = client
7
+ end
8
+
9
+ def list(limit: nil, before_seq: nil, action: nil, timeout: nil)
10
+ query = { "limit" => limit, "before_seq" => before_seq, "action" => action }.compact
11
+ @client.call("GET", "/v1/audit", query: query, timeout: timeout)
12
+ end
13
+
14
+ def verify(timeout: nil)
15
+ @client.call("GET", "/v1/audit/verify", timeout: timeout)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class Batch
5
+ MAX_ITEMS = 500
6
+ TERMINAL_STATUSES = %w[completed completed_with_errors failed].freeze
7
+
8
+ def initialize(client)
9
+ @client = client
10
+ end
11
+
12
+ def submit(items, convert_type: nil, mixed: false, webhook_url: nil, idempotency_key: nil, timeout: nil)
13
+ items = Array(items)
14
+ unless items.length.between?(1, MAX_ITEMS)
15
+ raise Sigli.invalid_argument("batch must contain 1..#{MAX_ITEMS} items (got #{items.length})")
16
+ end
17
+
18
+ body = { "items" => items.map { |i| Files.normalize_body(i) } }
19
+ body["webhook_url"] = webhook_url if webhook_url
20
+ headers = {}
21
+ headers["X-Convert-Type"] = convert_type.to_s if convert_type
22
+ headers["X-Batch-Mode"] = "mixed" if mixed
23
+ @client.call("POST", "/v1/batch/submit", body: body, headers: headers,
24
+ idempotency_key: idempotency_key, timeout: timeout)
25
+ end
26
+
27
+ def get(batch_id, timeout: nil)
28
+ @client.call("GET", "/v1/batch/#{Client.escape(batch_id)}", timeout: timeout)
29
+ end
30
+
31
+ def list(timeout: nil)
32
+ @client.call("GET", "/v1/batch", timeout: timeout)
33
+ end
34
+
35
+ def wait(batch_id, poll_interval: 1.0, max_interval: 10.0, timeout: 600)
36
+ deadline = monotonic + timeout
37
+ interval = poll_interval
38
+ loop do
39
+ data = get(batch_id)
40
+ return data if TERMINAL_STATUSES.include?(data["status"])
41
+
42
+ remaining = deadline - monotonic
43
+ if remaining <= 0
44
+ raise Error.new("batch #{batch_id} did not finish within #{timeout}s (last status: #{data['status']})",
45
+ code: "batch_timeout", body: data)
46
+ end
47
+
48
+ @client.sleeper.call([interval, remaining].min)
49
+ interval = [interval * 1.5, max_interval].min
50
+ end
51
+ end
52
+
53
+ private
54
+
55
+ def monotonic
56
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,278 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "time"
7
+ require "uri"
8
+
9
+ module Sigli
10
+ class Client
11
+ DEFAULT_BASE_URL = "https://api.sigli.dev"
12
+ RETRYABLE_STATUSES = [429, 502, 503, 504].freeze
13
+ NON_RETRYABLE_CODES = { 429 => "quota_exceeded", 503 => "feature_unavailable" }.freeze
14
+ IDEMPOTENT_METHODS = %w[GET HEAD PUT DELETE OPTIONS].freeze
15
+ MAX_BACKOFF = 8.0
16
+ MAX_RETRY_AFTER = 60.0
17
+
18
+ Response = Struct.new(:status, :content_type, :request_id, :retry_after, :body, :path, keyword_init: true) do
19
+ def json?
20
+ content_type.to_s.downcase.include?("application/json")
21
+ end
22
+
23
+ def parsed
24
+ return nil if body.nil? || body.empty?
25
+
26
+ JSON.parse(body.dup.force_encoding(Encoding::UTF_8))
27
+ end
28
+ end
29
+
30
+ attr_reader :base_url, :timeout, :max_retries, :pdf, :ai, :batch, :workflows, :webhooks, :audit
31
+ attr_accessor :sleeper
32
+
33
+ def self.verify_webhook_signature(payload, header, secret)
34
+ Webhook.verify_signature(payload, header, secret)
35
+ end
36
+
37
+ def self.compute_trigger_signature(secret, timestamp, body)
38
+ Webhook.compute_trigger_signature(secret, timestamp, body)
39
+ end
40
+
41
+ def self.escape(segment)
42
+ segment.to_s.b.gsub(/[^A-Za-z0-9_.~-]/) { |c| format("%%%02X", c.ord) }
43
+ end
44
+
45
+ def initialize(api_key: nil, base_url: nil, timeout: 60, max_retries: 2)
46
+ @api_key = api_key || ENV.fetch("SIGLI_API_KEY", nil)
47
+ raise Error.new("missing API key: pass api_key: or set SIGLI_API_KEY", code: "missing_api_key") if @api_key.nil? || @api_key.empty?
48
+
49
+ @base_url = (base_url || ENV["SIGLI_BASE_URL"] || DEFAULT_BASE_URL).to_s.sub(%r{/+\z}, "")
50
+ @timeout = timeout
51
+ @max_retries = max_retries
52
+ @sleeper = ->(seconds) { sleep(seconds) }
53
+ @pdf = PDF.new(self)
54
+ @ai = AI.new(self)
55
+ @batch = Batch.new(self)
56
+ @workflows = Workflows.new(self)
57
+ @webhooks = Webhooks.new(self)
58
+ @audit = Audit.new(self)
59
+ end
60
+
61
+ def inspect
62
+ "#<Sigli::Client base_url=#{@base_url.inspect}>"
63
+ end
64
+
65
+ def request(method, path, body: nil, query: nil, headers: nil, idempotency_key: nil, output_path: nil, timeout: nil)
66
+ resp = perform(method, path, body: body, query: query, headers: headers,
67
+ idempotency_key: idempotency_key, output_path: output_path, timeout: timeout)
68
+ return resp.path if resp.path
69
+
70
+ resp.json? ? resp.parsed : resp.body
71
+ end
72
+
73
+ def call(method, path, **opts)
74
+ unwrap(perform(method, path, **opts))
75
+ end
76
+
77
+ def process(convert_type, body = {}, idempotency_key: nil, output_path: nil, timeout: nil)
78
+ call("POST", "/v1/process", body: Files.normalize_body(body),
79
+ headers: { "X-Convert-Type" => convert_type.to_s },
80
+ idempotency_key: idempotency_key, output_path: output_path, timeout: timeout)
81
+ end
82
+
83
+ def html_to_pdf(html, idempotency_key: nil, output_path: nil, timeout: nil, **params)
84
+ process("html-to-pdf", params.merge(source: html),
85
+ idempotency_key: idempotency_key, output_path: output_path, timeout: timeout)
86
+ end
87
+
88
+ def url_to_pdf(url, idempotency_key: nil, output_path: nil, timeout: nil, **params)
89
+ process("url-to-pdf", params.merge(source_url: url),
90
+ idempotency_key: idempotency_key, output_path: output_path, timeout: timeout)
91
+ end
92
+
93
+ def screenshot(target, idempotency_key: nil, output_path: nil, timeout: nil, **params)
94
+ key = Files.url?(target) ? :source_url : :source
95
+ process("screenshot", params.merge(key => target),
96
+ idempotency_key: idempotency_key, output_path: output_path, timeout: timeout)
97
+ end
98
+
99
+ def ocr(file, idempotency_key: nil, timeout: nil, **params)
100
+ process("ocr", params.merge(file: file), idempotency_key: idempotency_key, timeout: timeout)
101
+ end
102
+
103
+ def pdf_to_markdown(file, idempotency_key: nil, timeout: nil, **params)
104
+ process("pdf-to-markdown", params.merge(file: file), idempotency_key: idempotency_key, timeout: timeout)
105
+ end
106
+
107
+ def wait_for_batch(batch_id, **opts)
108
+ @batch.wait(batch_id, **opts)
109
+ end
110
+
111
+ def unwrap(resp)
112
+ return resp.path if resp.path
113
+ return resp.body unless resp.json?
114
+
115
+ parsed = resp.parsed
116
+ parsed.is_a?(Hash) && parsed.key?("data") ? parsed["data"] : parsed
117
+ end
118
+
119
+ def perform(method, path, body: nil, query: nil, headers: nil, idempotency_key: nil, output_path: nil, timeout: nil)
120
+ method = method.to_s.upcase
121
+ req_headers = default_headers
122
+ (headers || {}).each { |k, v| req_headers[k.to_s] = v.to_s }
123
+ unless idempotency_key.nil?
124
+ key = idempotency_key.to_s.strip
125
+ unless key.length.between?(1, 128)
126
+ raise Error.new("idempotency key must be 1-128 characters", code: "invalid_idempotency_key")
127
+ end
128
+
129
+ req_headers["Idempotency-Key"] = key
130
+ end
131
+ payload = encode_body(body, req_headers)
132
+ uri = build_uri(path, query)
133
+ can_retry = IDEMPOTENT_METHODS.include?(method) || !idempotency_key.nil?
134
+ attempt = 0
135
+
136
+ loop do
137
+ begin
138
+ resp = execute(method, uri, req_headers, payload, output_path, timeout || @timeout)
139
+ rescue ConnectionError
140
+ raise unless can_retry && attempt < @max_retries
141
+
142
+ @sleeper.call(backoff(attempt))
143
+ attempt += 1
144
+ next
145
+ end
146
+ return resp if resp.status.between?(200, 299)
147
+
148
+ error = build_error(resp)
149
+ raise error unless can_retry && attempt < @max_retries && retryable?(error)
150
+
151
+ @sleeper.call(error.retry_after || backoff(attempt))
152
+ attempt += 1
153
+ end
154
+ end
155
+
156
+ private
157
+
158
+ def default_headers
159
+ {
160
+ "X-API-Key" => @api_key,
161
+ "User-Agent" => "sigli-ruby/#{VERSION}",
162
+ "Accept" => "application/json, */*"
163
+ }
164
+ end
165
+
166
+ def encode_body(body, headers)
167
+ case body
168
+ when nil then nil
169
+ when String
170
+ headers["Content-Type"] = "application/octet-stream" unless headers.keys.any? { |k| k.casecmp?("content-type") }
171
+ body.b
172
+ else
173
+ headers["Content-Type"] = "application/json"
174
+ JSON.generate(body)
175
+ end
176
+ end
177
+
178
+ def build_uri(path, query)
179
+ path = "/#{path}" unless path.start_with?("/")
180
+ uri = URI.parse(@base_url + path)
181
+ if query && !query.empty?
182
+ extra = URI.encode_www_form(query.to_h.compact)
183
+ uri.query = [uri.query, extra].compact.reject(&:empty?).join("&")
184
+ end
185
+ uri
186
+ end
187
+
188
+ def execute(method, uri, headers, payload, output_path, timeout)
189
+ req = Net::HTTPGenericRequest.new(method, !payload.nil?, method != "HEAD", uri.request_uri, headers)
190
+ req.body = payload if payload
191
+ http = Net::HTTP.new(uri.host, uri.port)
192
+ http.use_ssl = uri.scheme == "https"
193
+ http.open_timeout = timeout
194
+ http.read_timeout = timeout
195
+ http.write_timeout = timeout
196
+ http.max_retries = 0
197
+ result = nil
198
+ http.start do |conn|
199
+ conn.request(req) do |res|
200
+ result = read_response(res, output_path)
201
+ end
202
+ end
203
+ result
204
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
205
+ raise ConnectionError.new("request timed out: #{e.message}", code: "timeout")
206
+ rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
207
+ raise ConnectionError.new("network error: #{e.class}: #{e.message}", code: "network_error")
208
+ end
209
+
210
+ def read_response(res, output_path)
211
+ status = res.code.to_i
212
+ meta = {
213
+ status: status,
214
+ content_type: res["content-type"],
215
+ request_id: res["x-request-id"],
216
+ retry_after: res["retry-after"]
217
+ }
218
+ json = meta[:content_type].to_s.downcase.include?("application/json")
219
+ if output_path && status.between?(200, 299) && !json
220
+ stream_to_file(res, output_path)
221
+ return Response.new(**meta, path: output_path)
222
+ end
223
+
224
+ body = String.new(encoding: Encoding::BINARY)
225
+ res.read_body { |chunk| body << chunk }
226
+ Response.new(**meta, body: body)
227
+ end
228
+
229
+ def stream_to_file(res, output_path)
230
+ File.open(output_path, "wb") do |f|
231
+ res.read_body { |chunk| f.write(chunk) }
232
+ end
233
+ rescue StandardError
234
+ File.delete(output_path) if File.exist?(output_path)
235
+ raise
236
+ end
237
+
238
+ def build_error(resp)
239
+ parsed = begin
240
+ resp.parsed
241
+ rescue JSON::ParserError
242
+ nil
243
+ end
244
+ text = resp.body.to_s.dup.force_encoding(Encoding::UTF_8)
245
+ if parsed.is_a?(Hash) && (parsed["code"] || parsed["message"])
246
+ code = parsed["code"] || "http_#{resp.status}"
247
+ message = parsed["message"] || "HTTP #{resp.status}"
248
+ else
249
+ code = "http_#{resp.status}"
250
+ message = text.strip.empty? ? "HTTP #{resp.status}" : text[0, 500]
251
+ end
252
+ Error.new(message, status: resp.status, code: code, request_id: resp.request_id,
253
+ body: parsed || text, retry_after: parse_retry_after(resp.retry_after))
254
+ end
255
+
256
+ def retryable?(error)
257
+ RETRYABLE_STATUSES.include?(error.status) && NON_RETRYABLE_CODES[error.status] != error.code
258
+ end
259
+
260
+ def backoff(attempt)
261
+ base = [MAX_BACKOFF, 0.5 * (2**attempt)].min
262
+ (base / 2) + (rand * base / 2)
263
+ end
264
+
265
+ def parse_retry_after(value)
266
+ return nil if value.nil? || value.strip.empty?
267
+
268
+ seconds = if value.strip.match?(/\A\d+(\.\d+)?\z/)
269
+ value.to_f
270
+ else
271
+ Time.httpdate(value.strip) - Time.now
272
+ end
273
+ seconds.clamp(0.0, MAX_RETRY_AFTER)
274
+ rescue ArgumentError
275
+ nil
276
+ end
277
+ end
278
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class Error < StandardError
5
+ attr_reader :status, :code, :request_id, :body, :retry_after
6
+
7
+ def initialize(message = nil, status: 0, code: "error", request_id: nil, body: nil, retry_after: nil)
8
+ super(message || code)
9
+ @status = status
10
+ @code = code
11
+ @request_id = request_id
12
+ @body = body
13
+ @retry_after = retry_after
14
+ end
15
+
16
+ def detailed_message(highlight: false, **)
17
+ parts = ["code=#{code}"]
18
+ parts << "status=#{status}" if status.positive?
19
+ parts << "request_id=#{request_id}" if request_id
20
+ "#{super} (#{parts.join(' ')})"
21
+ end
22
+ end
23
+
24
+ class ConnectionError < Error; end
25
+
26
+ def self.invalid_argument(message)
27
+ Error.new(message, code: "invalid_argument")
28
+ end
29
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ module Sigli
6
+ module Files
7
+ URL_PATTERN = %r{\Ahttps?://}i.freeze
8
+
9
+ module_function
10
+
11
+ def url?(value)
12
+ value.is_a?(String) && URL_PATTERN.match?(value)
13
+ end
14
+
15
+ def encode(bytes)
16
+ [bytes].pack("m0")
17
+ end
18
+
19
+ def resolve(input)
20
+ case input
21
+ when Pathname
22
+ [:base64, encode(read_path(input.to_s))]
23
+ when String
24
+ if url?(input)
25
+ [:url, input]
26
+ elsif input.encoding == Encoding::BINARY
27
+ [:base64, encode(input)]
28
+ else
29
+ [:base64, encode(read_path(input))]
30
+ end
31
+ else
32
+ raise Sigli.invalid_argument("unsupported file input: #{input.class}") unless input.respond_to?(:read)
33
+
34
+ [:base64, encode(input.read.to_s.b)]
35
+ end
36
+ end
37
+
38
+ def base64_only(input, field)
39
+ kind, value = resolve(input)
40
+ raise Sigli.invalid_argument("#{field} must be bytes, a path or an IO, not a URL") if kind == :url
41
+
42
+ value
43
+ end
44
+
45
+ def apply(body, input)
46
+ kind, value = resolve(input)
47
+ body[kind == :url ? "file_url" : "file_base64"] = value
48
+ body
49
+ end
50
+
51
+ def normalize_body(body)
52
+ out = (body || {}).to_h.transform_keys(&:to_s)
53
+ file = out.delete("file")
54
+ apply(out, file) unless file.nil?
55
+ out
56
+ end
57
+
58
+ def read_path(path)
59
+ raise Sigli.invalid_argument("file not found: #{path}") unless File.file?(path)
60
+
61
+ File.binread(path)
62
+ end
63
+ end
64
+ end
data/lib/sigli/pdf.rb ADDED
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class PDF
5
+ def initialize(client)
6
+ @client = client
7
+ end
8
+
9
+ def merge(files, idempotency_key: nil, output_path: nil, timeout: nil, **params)
10
+ files = Array(files)
11
+ raise Sigli.invalid_argument("merge requires at least 2 files") if files.length < 2
12
+
13
+ encoded = []
14
+ urls = []
15
+ files.each do |f|
16
+ kind, value = Files.resolve(f)
17
+ if kind == :url
18
+ urls << value
19
+ else
20
+ raise Sigli.invalid_argument("merge: URL inputs must come after all byte/path inputs (server merges uploaded files first)") unless urls.empty?
21
+
22
+ encoded << value
23
+ end
24
+ end
25
+ body = stringify(params)
26
+ body["files"] = encoded unless encoded.empty?
27
+ body["file_urls"] = urls unless urls.empty?
28
+ post("merge", body, idempotency_key, output_path, timeout)
29
+ end
30
+
31
+ def split(file, pages, **opts)
32
+ op("split", file, { "pages" => pages }, **opts)
33
+ end
34
+
35
+ def compress(file, **opts)
36
+ op("compress", file, {}, **opts)
37
+ end
38
+
39
+ def rotate(file, **opts)
40
+ op("rotate", file, {}, **opts)
41
+ end
42
+
43
+ def watermark(file, image: nil, **opts)
44
+ extra = {}
45
+ extra["image_base64"] = Files.base64_only(image, "image") unless image.nil?
46
+ op("watermark", file, extra, **opts)
47
+ end
48
+
49
+ def protect(file, **opts)
50
+ op("protect", file, {}, **opts)
51
+ end
52
+
53
+ def unlock(file, password, **opts)
54
+ op("unlock", file, { "password" => password }, **opts)
55
+ end
56
+
57
+ def redact(file, regions, **opts)
58
+ op("redact", file, { "regions" => regions }, **opts)
59
+ end
60
+
61
+ def page_numbers(file, **opts)
62
+ op("page-numbers", file, {}, **opts)
63
+ end
64
+
65
+ def remove_pages(file, pages, **opts)
66
+ op("remove-pages", file, { "pages" => pages }, **opts)
67
+ end
68
+
69
+ def reorder(file, order, **opts)
70
+ op("reorder", file, { "order" => order }, **opts)
71
+ end
72
+
73
+ def metadata(file, **opts)
74
+ op("metadata", file, {}, **opts)
75
+ end
76
+
77
+ def info(file, **opts)
78
+ op("info", file, {}, **opts)
79
+ end
80
+
81
+ def forms_extract(file, **opts)
82
+ op("forms/extract", file, {}, **opts)
83
+ end
84
+
85
+ def forms_fill(file, fields, **opts)
86
+ op("forms/fill", file, { "fields" => fields }, **opts)
87
+ end
88
+
89
+ def to_images(file, **opts)
90
+ op("to-images", file, {}, **opts)
91
+ end
92
+
93
+ def pdfa(file, level: "2b", **opts)
94
+ op("pdfa", file, { "level" => level }, **opts)
95
+ end
96
+
97
+ def compare(old_file, new_file, idempotency_key: nil, output_path: nil, timeout: nil, **params)
98
+ body = stringify(params)
99
+ [["old", old_file], ["new", new_file]].each do |prefix, input|
100
+ kind, value = Files.resolve(input)
101
+ body[kind == :url ? "#{prefix}_file_url" : "#{prefix}_file_base64"] = value
102
+ end
103
+ post("compare", body, idempotency_key, output_path, timeout)
104
+ end
105
+
106
+ def sign(file, certificate:, certificate_password:, **opts)
107
+ extra = {
108
+ "certificate_base64" => Files.base64_only(certificate, "certificate"),
109
+ "certificate_password" => certificate_password
110
+ }
111
+ op("sign", file, extra, **opts)
112
+ end
113
+
114
+ def verify_signatures(file, **opts)
115
+ op("signatures/verify", file, {}, **opts)
116
+ end
117
+
118
+ def detect_form_fields(file, **opts)
119
+ op("forms/detect", file, {}, **opts)
120
+ end
121
+
122
+ private
123
+
124
+ def op(name, file, extra, idempotency_key: nil, output_path: nil, timeout: nil, **params)
125
+ body = Files.apply(stringify(params).merge(extra), file)
126
+ post(name, body, idempotency_key, output_path, timeout)
127
+ end
128
+
129
+ def post(name, body, idempotency_key, output_path, timeout)
130
+ @client.call("POST", "/v1/pdf/#{name}", body: body, idempotency_key: idempotency_key,
131
+ output_path: output_path, timeout: timeout)
132
+ end
133
+
134
+ def stringify(params)
135
+ params.transform_keys(&:to_s)
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Sigli
6
+ module Webhook
7
+ HEX_SIGNATURE = /\A[0-9a-f]{64}\z/.freeze
8
+
9
+ module_function
10
+
11
+ def verify_signature(payload, header, secret)
12
+ return false if payload.nil? || header.nil? || secret.nil? || secret.to_s.empty?
13
+
14
+ sig = header.to_s.strip
15
+ sig = sig[7..] if sig.downcase.start_with?("sha256=")
16
+ sig = sig.to_s.strip.downcase
17
+ return false unless HEX_SIGNATURE.match?(sig)
18
+
19
+ expected = OpenSSL::HMAC.hexdigest("SHA256", secret.to_s.b, payload.to_s.b)
20
+ OpenSSL.fixed_length_secure_compare(expected, sig)
21
+ rescue StandardError
22
+ false
23
+ end
24
+
25
+ def compute_trigger_signature(secret, timestamp, body)
26
+ raise Sigli.invalid_argument("secret is required") if secret.nil? || secret.to_s.empty?
27
+
28
+ "sha256=#{OpenSSL::HMAC.hexdigest("SHA256", secret.to_s.b, "#{timestamp.to_i}.".b + body.to_s.b)}"
29
+ end
30
+ end
31
+
32
+ def self.verify_webhook_signature(payload, header, secret)
33
+ Webhook.verify_signature(payload, header, secret)
34
+ end
35
+
36
+ def self.compute_trigger_signature(secret, timestamp, body)
37
+ Webhook.compute_trigger_signature(secret, timestamp, body)
38
+ end
39
+
40
+ class Webhooks
41
+ def initialize(client)
42
+ @client = client
43
+ end
44
+
45
+ def list(timeout: nil)
46
+ @client.call("GET", "/webhooks", timeout: timeout)
47
+ end
48
+
49
+ def create(url, events, idempotency_key: nil, timeout: nil)
50
+ @client.call("POST", "/webhooks", body: { "url" => url, "events" => Array(events) },
51
+ idempotency_key: idempotency_key, timeout: timeout)
52
+ end
53
+
54
+ def delete(webhook_id, timeout: nil)
55
+ @client.call("DELETE", "/webhooks/#{Client.escape(webhook_id)}", timeout: timeout)
56
+ true
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sigli
4
+ class Workflows
5
+ attr_reader :triggers
6
+
7
+ def initialize(client)
8
+ @client = client
9
+ @triggers = Triggers.new(client)
10
+ end
11
+
12
+ def list(timeout: nil)
13
+ @client.call("GET", "/v1/workflows", timeout: timeout)
14
+ end
15
+
16
+ def get(workflow_id, timeout: nil)
17
+ @client.call("GET", "/v1/workflows/#{Client.escape(workflow_id)}", timeout: timeout)
18
+ end
19
+
20
+ def create(name:, steps:, description: nil, idempotency_key: nil, timeout: nil)
21
+ body = { "name" => name, "steps" => steps }
22
+ body["description"] = description if description
23
+ @client.call("POST", "/v1/workflows", body: body, idempotency_key: idempotency_key, timeout: timeout)
24
+ end
25
+
26
+ def run(workflow_id, input = {}, webhook: nil, tag: nil, idempotency_key: nil, timeout: nil)
27
+ body = { "input" => Files.normalize_body(input) }
28
+ body["webhook"] = webhook if webhook
29
+ body["tag"] = tag if tag
30
+ @client.call("POST", "/v1/workflows/#{Client.escape(workflow_id)}/run",
31
+ body: body, idempotency_key: idempotency_key, timeout: timeout)
32
+ end
33
+
34
+ def runs(workflow_id, timeout: nil)
35
+ @client.call("GET", "/v1/workflows/#{Client.escape(workflow_id)}/runs", timeout: timeout)
36
+ end
37
+ end
38
+
39
+ class Triggers
40
+ def initialize(client)
41
+ @client = client
42
+ end
43
+
44
+ def create(workflow_id, idempotency_key: nil, timeout: nil, **params)
45
+ @client.call("POST", path(workflow_id), body: params.transform_keys(&:to_s),
46
+ idempotency_key: idempotency_key, timeout: timeout)
47
+ end
48
+
49
+ def list(workflow_id, timeout: nil)
50
+ @client.call("GET", path(workflow_id), timeout: timeout)
51
+ end
52
+
53
+ def revoke(workflow_id, trigger_id, timeout: nil)
54
+ @client.call("DELETE", "#{path(workflow_id)}/#{Client.escape(trigger_id)}", timeout: timeout)
55
+ end
56
+
57
+ private
58
+
59
+ def path(workflow_id)
60
+ "/v1/workflows/#{Client.escape(workflow_id)}/triggers"
61
+ end
62
+ end
63
+ end
data/lib/sigli.rb ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sigli/version"
4
+ require_relative "sigli/errors"
5
+ require_relative "sigli/files"
6
+ require_relative "sigli/webhooks"
7
+ require_relative "sigli/pdf"
8
+ require_relative "sigli/ai"
9
+ require_relative "sigli/batch"
10
+ require_relative "sigli/workflows"
11
+ require_relative "sigli/audit"
12
+ require_relative "sigli/client"
13
+
14
+ module Sigli
15
+ def self.new(**opts)
16
+ Client.new(**opts)
17
+ end
18
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sigli
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sigli
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: HTML/URL to PDF, OCR, PDF tools, AI extraction, batch jobs, workflows
13
+ and webhook verification for the Sigli API. Stdlib only.
14
+ email:
15
+ - help@sigli.dev
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/sigli.rb
23
+ - lib/sigli/ai.rb
24
+ - lib/sigli/audit.rb
25
+ - lib/sigli/batch.rb
26
+ - lib/sigli/client.rb
27
+ - lib/sigli/errors.rb
28
+ - lib/sigli/files.rb
29
+ - lib/sigli/pdf.rb
30
+ - lib/sigli/version.rb
31
+ - lib/sigli/webhooks.rb
32
+ - lib/sigli/workflows.rb
33
+ homepage: https://sigli.dev
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://sigli.dev
38
+ documentation_uri: https://sigli.dev/quickstart
39
+ rubygems_mfa_required: 'true'
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 4.0.23
55
+ specification_version: 4
56
+ summary: Official Ruby client for the Sigli document API
57
+ test_files: []