backlex 0.0.1

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: 01f91fb97df5e3be829a139e6f6b8ca5ed6db3ff6964e23fbe98993f88aaca36
4
+ data.tar.gz: 9846419c9ad1c7b62322a311538a2c88e0dbd2aa579f418c865602d07c268fcf
5
+ SHA512:
6
+ metadata.gz: 9253fd5739603b9ae274ef5d80a401d7b2e18a88cffe9aaeec8fd25407be4a128cac8ae4d81fc73bb76a73ae58a19d0106300305bb271cf3df779cebc0654886
7
+ data.tar.gz: 56c161ee05698e5c476bb8bd1c17975baf6bd4d937e6bf1793e61241030707909c55cf0fb7cfd147a3dbf2fae4a99a5432f31a2b5d6fe2f1e4bcb94a0d50eecc
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work, excluding
103
+ those notices that do not pertain to any part of the Derivative
104
+ Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Furkan Kınyas
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,120 @@
1
+ # backlex — Ruby SDK
2
+
3
+ Official Ruby client for the backlex API. A thin wrapper over the same REST + SSE
4
+ surface the TypeScript SDK (`@backlex/client`) speaks — CRUD, a fluent query
5
+ builder, auth, realtime, and storage. **Zero runtime dependencies** (stdlib
6
+ `net/http` + `json`).
7
+
8
+ Part of backlex's multi-language SDK effort; follows the **hybrid** model:
9
+ hand-written ergonomic layer here, optional OpenAPI-generated models underneath.
10
+
11
+ ```bash
12
+ gem install backlex # not yet published
13
+ ```
14
+
15
+ ## Quickstart
16
+
17
+ ```ruby
18
+ require "backlex"
19
+ F = Backlex::Filter
20
+
21
+ client = Backlex::Client.new("https://api.example.com", api_key: "pak_...")
22
+
23
+ # CRUD
24
+ created = client.from("posts").create({ "title" => "Hello" })
25
+ client.from("posts").update(created["data"]["id"], { "title" => "Edited" })
26
+ client.from("posts").delete(created["data"]["id"])
27
+
28
+ # Fluent query builder → compiles to canonical JSON (same wire format as every other SDK)
29
+ rows = client.from("orders").query
30
+ .where(F.and_(
31
+ F.eq("status", "active"),
32
+ F.gte("total", 100),
33
+ F.rel("customer", F.eq("tier", "gold")), # -> "customer.tier"
34
+ F.gte("placed_at", F.now(sub: { "months" => 1 }))
35
+ ))
36
+ .select("id", "total", "customer.name")
37
+ .order_by("-placed_at", "id")
38
+ .limit(50)
39
+ .list
40
+ ```
41
+
42
+ Ruby keywords are suffixed with `_`: `and_`, `or_`, `not_`, `in_`.
43
+
44
+ ## Auth
45
+
46
+ ```ruby
47
+ # Server-to-server: Backlex::Client.new(url, api_key: "pak_...") — bearer on every call.
48
+
49
+ # App mode — end-users of a workspace:
50
+ client = Backlex::Client.new(url, workspace: "myapp")
51
+ res = client.auth.sign_in("user@example.com", "secret") # token auto-captured
52
+ token = client.auth.token # persist this
53
+ # later: Backlex::Client.new(url, workspace: "myapp", token: token)
54
+ client.auth.sign_out
55
+ ```
56
+
57
+ `client.auth.providers` returns the public auth surface. `sign_in_social` and
58
+ `sign_in_magic_link` are also available.
59
+
60
+ ## Realtime (SSE)
61
+
62
+ ```ruby
63
+ sub = client.subscribe("items:posts", ->(ev) { puts "#{ev['event']}: #{ev['data']}" })
64
+ # ... runs on a background thread, auto-reconnects ...
65
+ sub.close
66
+ ```
67
+
68
+ ## Storage
69
+
70
+ ```ruby
71
+ client.storage.put("avatars/me.png", bytes, content_type: "image/png")
72
+ data = client.storage.download("avatars/me.png")
73
+ client.storage.list("avatars/")
74
+ client.storage.delete("avatars/me.png")
75
+ ```
76
+
77
+ ## Errors
78
+
79
+ Every non-2xx response (and transport failures) raise `Backlex::Error` with
80
+ `#status`, `#code`, `#details`:
81
+
82
+ ```ruby
83
+ begin
84
+ client.from("missing").list
85
+ rescue Backlex::Error => e
86
+ raise unless e.status == 404
87
+ end
88
+ ```
89
+
90
+ ## Hybrid codegen
91
+
92
+ For **typed models**, generate them from the OpenAPI spec the server ships — no
93
+ Ruby-specific wire format is introduced:
94
+
95
+ ```bash
96
+ openapi-generator generate \
97
+ -i apps/web/src/server/lib/openapi-static.generated.json \
98
+ -g ruby -o sdks/ruby/generated
99
+ ```
100
+
101
+ ## Develop
102
+
103
+ ```bash
104
+ cd sdks/ruby
105
+ ruby -Ilib test/query_test.rb # offline: query-builder contract
106
+ ruby -Ilib test/client_test.rb # offline: WEBrick HTTP-layer contract
107
+ ```
108
+
109
+ ## Parity with the TS SDK
110
+
111
+ | TS (`@backlex/client`) | Ruby (`Backlex`) |
112
+ | -------------------------- | --------------------------------------------- |
113
+ | `createClient(opts)` | `Backlex::Client.new(url, api_key:/workspace:/token:)` |
114
+ | `client.from(slug)` | `client.from(slug)` |
115
+ | `.query().where(f => ...)` | `.query.where(Filter.and_(...))` |
116
+ | `f.eq / and / rel / now` | `Filter.eq / and_ / rel / now` |
117
+ | `.orderBy().withMeta()` | `.order_by.with_meta` |
118
+ | `client.subscribe(ch, cb)` | `client.subscribe(ch, cb)` → `.close` |
119
+ | `auth.signIn / getToken` | `client.auth.sign_in / token` |
120
+ | `BacklexError` | `Backlex::Error` |
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Backlex
6
+ # Auth surface. In app mode (workspace set) calls target that workspace's own
7
+ # auth pool ("/api/t/<slug>/auth/..."); otherwise the control plane.
8
+ class Auth
9
+ def initialize(client)
10
+ @client = client
11
+ end
12
+
13
+ def sign_up(email, password, name = nil)
14
+ body = { "email" => email, "password" => password }
15
+ body["name"] = name if name
16
+ capture(@client.request("POST", "#{base}/sign-up/email", body))
17
+ end
18
+
19
+ def sign_in(email, password)
20
+ capture(@client.request("POST", "#{base}/sign-in/email", { "email" => email, "password" => password }))
21
+ end
22
+
23
+ # Begin an OAuth sign-in; navigate the user to the returned URL.
24
+ def sign_in_social(provider, callback_url: nil, error_callback_url: nil)
25
+ body = { "provider" => provider, "disableRedirect" => true }
26
+ body["callbackURL"] = callback_url if callback_url
27
+ body["errorCallbackURL"] = error_callback_url if error_callback_url
28
+ @client.request("POST", "#{base}/sign-in/social", body)
29
+ end
30
+
31
+ # Send a one-time sign-in link by email.
32
+ def sign_in_magic_link(email, callback_url: nil)
33
+ body = { "email" => email }
34
+ body["callbackURL"] = callback_url if callback_url
35
+ @client.request("POST", "#{base}/sign-in/magic-link", body)
36
+ end
37
+
38
+ # Email a one-time numeric code (requires the email-otp provider). +type+ is
39
+ # "sign-in" (default), "email-verification" or "forget-password". Complete a
40
+ # sign-in with #sign_in_email_otp.
41
+ def send_verification_otp(email, type: "sign-in")
42
+ @client.request("POST", "#{base}/email-otp/send-verification-otp", { "email" => email, "type" => type })
43
+ end
44
+
45
+ # Complete an email-OTP sign-in with the code from #send_verification_otp. In
46
+ # app mode the returned session token is captured.
47
+ def sign_in_email_otp(email, otp)
48
+ capture(@client.request("POST", "#{base}/sign-in/email-otp", { "email" => email, "otp" => otp }))
49
+ end
50
+
51
+ # Clear the session; in app mode also drops the captured token.
52
+ # Send a password-reset email. +redirect_to+ is the link target.
53
+ def request_password_reset(email, redirect_to: nil)
54
+ body = { "email" => email }
55
+ body["redirectTo"] = redirect_to if redirect_to
56
+ @client.request("POST", "#{base}/request-password-reset", body)
57
+ end
58
+
59
+ # Complete a reset with the token from the email and a new password.
60
+ def reset_password(new_password, token)
61
+ @client.request("POST", "#{base}/reset-password", { "newPassword" => new_password, "token" => token })
62
+ end
63
+
64
+ # Mint a fresh access JWT from the stored session token (app mode).
65
+ def refresh
66
+ @client.request("POST", "#{base}/token/refresh", { "refreshToken" => @client.app_token })
67
+ end
68
+
69
+ # Change the signed-in user's password (requires the current password).
70
+ def change_password(new_password, current_password, revoke_other_sessions: false)
71
+ @client.request("POST", "#{base}/change-password", {
72
+ "newPassword" => new_password,
73
+ "currentPassword" => current_password,
74
+ "revokeOtherSessions" => revoke_other_sessions
75
+ })
76
+ end
77
+
78
+ # Update the signed-in user's profile (e.g. name / image).
79
+ def update_user(attributes)
80
+ @client.request("POST", "#{base}/update-user", attributes)
81
+ end
82
+
83
+ # Send an email-verification link.
84
+ def send_verification_email(email, callback_url: nil)
85
+ body = { "email" => email }
86
+ body["callbackURL"] = callback_url if callback_url
87
+ @client.request("POST", "#{base}/send-verification-email", body)
88
+ end
89
+
90
+ def sign_out
91
+ @client.request("POST", "#{base}/sign-out")
92
+ @client.app_token = nil if workspace?
93
+ end
94
+
95
+ # Current session payload, or { "user" => nil }.
96
+ def session
97
+ @client.request("GET", "#{base}/get-session")
98
+ end
99
+
100
+ # List the signed-in user's active sessions (one row per device/login).
101
+ def list_sessions
102
+ @client.request("GET", "#{base}/list-sessions")
103
+ end
104
+
105
+ # Revoke one session by its +token+ (from #list_sessions).
106
+ def revoke_session(token)
107
+ @client.request("POST", "#{base}/revoke-session", { "token" => token })
108
+ end
109
+
110
+ # Revoke every session except the current one (sign out other devices).
111
+ def revoke_other_sessions
112
+ @client.request("POST", "#{base}/revoke-other-sessions")
113
+ end
114
+
115
+ # Revoke all sessions, including the current one.
116
+ def revoke_sessions
117
+ @client.request("POST", "#{base}/revoke-sessions")
118
+ end
119
+
120
+ # Public auth surface (provider list + policy flags).
121
+ def providers
122
+ @client.request("GET", "#{base}/providers")["data"]
123
+ end
124
+
125
+ # Current workspace session token (app mode); persist and restore via Client.new(token:).
126
+ def token
127
+ @client.app_token
128
+ end
129
+
130
+ # Restore a workspace session token (app mode).
131
+ def token=(value)
132
+ @client.app_token = value
133
+ end
134
+
135
+ private
136
+
137
+ def workspace?
138
+ !(@client.workspace.nil? || @client.workspace.empty?)
139
+ end
140
+
141
+ def base
142
+ workspace? ? "/api/t/#{URI.encode_www_form_component(@client.workspace)}/auth" : "/api/auth"
143
+ end
144
+
145
+ def capture(result)
146
+ @client.app_token = result["token"] if workspace? && result.is_a?(Hash) && result["token"]
147
+ result
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module Backlex
8
+ # The official Ruby client for the backlex API — a thin, typed wrapper over the
9
+ # same REST + SSE surface the TypeScript SDK (@backlex/client) speaks. Three auth
10
+ # modes: server key, workspace app mode (token capture), or cookie session.
11
+ class Client
12
+ attr_reader :workspace
13
+ attr_accessor :app_token
14
+
15
+ def initialize(url, api_key: nil, workspace: nil, token: nil, tenant: nil)
16
+ @url = url.chomp("/")
17
+ @api_key = api_key
18
+ @workspace = workspace
19
+ @app_token = token
20
+ @tenant = tenant
21
+ end
22
+
23
+ # CRUD handle for a collection.
24
+ def from(slug)
25
+ Collection.new(self, slug)
26
+ end
27
+
28
+ def auth
29
+ @auth ||= Auth.new(self)
30
+ end
31
+
32
+ def storage
33
+ @storage ||= Storage.new(self)
34
+ end
35
+
36
+ # Subscribe to a realtime channel (e.g. "items:posts"). Returns a Subscription;
37
+ # #close unsubscribes. on_error may be nil.
38
+ def subscribe(channel, on_event, on_error = nil)
39
+ Subscription.new(self, "#{@url}/api/realtime/#{channel}/subscribe", on_event, on_error)
40
+ end
41
+
42
+ # Raw escape hatch — issues a JSON request with auth headers applied.
43
+ def request(method, path, body = nil)
44
+ uri = URI(@url + path)
45
+ req = build_request(method, uri)
46
+ req["Content-Type"] = "application/json"
47
+ req.body = JSON.generate(body) unless body.nil?
48
+ auth_header(req)
49
+ res = send_request(uri, req)
50
+ code = res.code.to_i
51
+ raise Backlex::Error.from(code, res.body) if code < 200 || code >= 300
52
+ return nil if code == 204 || res.body.nil? || res.body.empty?
53
+
54
+ JSON.parse(res.body)
55
+ end
56
+
57
+ # Raw-body upload (storage). Returns the parsed JSON response.
58
+ def put_raw(path, body, content_type)
59
+ uri = URI(@url + path)
60
+ req = Net::HTTP::Put.new(uri)
61
+ req["Content-Type"] = content_type if content_type
62
+ req.body = body
63
+ auth_header(req)
64
+ res = send_request(uri, req)
65
+ code = res.code.to_i
66
+ raise Backlex::Error.from(code, res.body) if code < 200 || code >= 300
67
+
68
+ res.body.nil? || res.body.empty? ? nil : JSON.parse(res.body)
69
+ end
70
+
71
+ # Raw byte download (storage). Returns the response body string.
72
+ def get_raw(path)
73
+ uri = URI(@url + path)
74
+ req = Net::HTTP::Get.new(uri)
75
+ auth_header(req)
76
+ res = send_request(uri, req)
77
+ code = res.code.to_i
78
+ raise Backlex::Error.new(code, "UNKNOWN", "HTTP #{code}") if code < 200 || code >= 300
79
+
80
+ res.body
81
+ end
82
+
83
+ def auth_header(req)
84
+ if @api_key
85
+ req["Authorization"] = "Bearer #{@api_key}"
86
+ elsif @app_token
87
+ req["Authorization"] = "Bearer #{@app_token}"
88
+ end
89
+ req["X-Backlex-Tenant"] = @tenant if @tenant
90
+ end
91
+
92
+ # Serialize a ListQuery hash into a URL query string (mirrors buildSearch in
93
+ # index.ts). The filter is compact JSON, percent-encoded exactly once.
94
+ def self.build_search(query)
95
+ return "" if query.nil?
96
+
97
+ parts = []
98
+ if query[:filter] && !query[:filter].empty?
99
+ parts << "filter=#{URI.encode_www_form_component(JSON.generate(query[:filter]))}"
100
+ end
101
+ # sort/fields may be absent when a hand-built query (e.g. one(id, expand:)) is
102
+ # passed rather than a full builder-produced ListQuery — default to [].
103
+ parts << "sort=#{URI.encode_www_form_component(query[:sort].join(','))}" unless (query[:sort] || []).empty?
104
+ parts << "fields=#{URI.encode_www_form_component(query[:fields].join(','))}" unless (query[:fields] || []).empty?
105
+ unless (query[:expand] || []).empty?
106
+ parts << "expand=#{URI.encode_www_form_component(query[:expand].join(','))}"
107
+ end
108
+ parts << "limit=#{query[:limit]}" unless query[:limit].nil?
109
+ parts << "offset=#{query[:offset]}" unless query[:offset].nil?
110
+ parts << "meta=#{URI.encode_www_form_component(query[:meta])}" if query[:meta]
111
+ parts << "locale=#{URI.encode_www_form_component(query[:locale])}" if query[:locale]
112
+ parts << "q=#{URI.encode_www_form_component(query[:q])}" if query[:q]
113
+ parts.empty? ? "" : "?#{parts.join('&')}"
114
+ end
115
+
116
+ private
117
+
118
+ def build_request(method, uri)
119
+ case method.upcase
120
+ when "GET" then Net::HTTP::Get.new(uri)
121
+ when "POST" then Net::HTTP::Post.new(uri)
122
+ when "PATCH" then Net::HTTP::Patch.new(uri)
123
+ when "PUT" then Net::HTTP::Put.new(uri)
124
+ when "DELETE" then Net::HTTP::Delete.new(uri)
125
+ else raise ArgumentError, "unsupported method #{method}"
126
+ end
127
+ end
128
+
129
+ def send_request(uri, req)
130
+ http = Net::HTTP.new(uri.host, uri.port)
131
+ http.use_ssl = uri.scheme == "https"
132
+ http.request(req)
133
+ rescue StandardError => e
134
+ raise Backlex::Error.new(0, "NETWORK", e.message)
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Backlex
4
+ # A CRUD handle for one collection. Obtain via client.from("slug").
5
+ class Collection
6
+ def initialize(client, slug)
7
+ @client = client
8
+ @slug = slug
9
+ end
10
+
11
+ def list(query = nil)
12
+ @client.request("GET", "/api/items/#{@slug}#{Client.build_search(query)}")
13
+ end
14
+
15
+ # Fluent builder that compiles to a ListQuery.
16
+ def query
17
+ QueryBuilder.new(method(:list))
18
+ end
19
+
20
+ # Single-function aggregate (count/sum/avg/min/max), optionally grouped.
21
+ # body = { "agg" => "sum", "field" => "price", "groupBy" => "status" }
22
+ def aggregate(body)
23
+ @client.request("POST", "/api/items/#{@slug}/aggregate", body)
24
+ end
25
+
26
+ # query may carry expand/locale, the same params the list endpoint accepts.
27
+ def one(id, query = nil)
28
+ @client.request("GET", "/api/items/#{@slug}/#{id}#{Client.build_search(query)}")
29
+ end
30
+
31
+ def create(data)
32
+ @client.request("POST", "/api/items/#{@slug}", data)
33
+ end
34
+
35
+ def update(id, patch)
36
+ @client.request("PATCH", "/api/items/#{@slug}/#{id}", patch)
37
+ end
38
+
39
+ def delete(id)
40
+ @client.request("DELETE", "/api/items/#{@slug}/#{id}")
41
+ end
42
+
43
+ # Flip a versioned item to published.
44
+ def publish(id)
45
+ @client.request("POST", "/api/items/#{@slug}/#{id}/publish")
46
+ end
47
+
48
+ # Flip a versioned item back to draft.
49
+ def unpublish(id)
50
+ @client.request("POST", "/api/items/#{@slug}/#{id}/publish?unpublish=1")
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Backlex
4
+ # A non-2xx response from the backlex API (or a transport failure), mirroring
5
+ # the TS SDK's BacklexError. The API returns errors as
6
+ # `{ "error": { "code", "message", "details"? } }`; callers branch on #status /
7
+ # #code rather than parsing strings.
8
+ class Error < StandardError
9
+ attr_reader :status, :code, :details
10
+
11
+ def initialize(status, code, message, details = nil)
12
+ super(message)
13
+ @status = status
14
+ @code = code
15
+ @details = details
16
+ end
17
+
18
+ # Parse the `{ "error": {...} }` envelope from a response body.
19
+ def self.from(status, body)
20
+ code = "UNKNOWN"
21
+ message = "HTTP #{status}"
22
+ details = nil
23
+ unless body.nil? || body.empty?
24
+ begin
25
+ env = JSON.parse(body)
26
+ err = env["error"]
27
+ if err.is_a?(Hash)
28
+ code = err["code"] if err["code"]
29
+ message = err["message"] if err["message"]
30
+ details = err["details"]
31
+ end
32
+ rescue JSON::ParserError
33
+ # non-JSON error body — keep the generic message
34
+ end
35
+ end
36
+ new(status, code, message, details)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Backlex
4
+ # Static condition constructors — a Ruby port of the leaf/logical helpers in
5
+ # query.ts. Compose them and pass to QueryBuilder#where. Everything compiles to
6
+ # the canonical JSON Condition the REST API speaks.
7
+ #
8
+ # rows = client.from("orders").query
9
+ # .where(Backlex::Filter.and_(
10
+ # Backlex::Filter.eq("status", "active"),
11
+ # Backlex::Filter.gte("total", 100),
12
+ # Backlex::Filter.rel("customer", Backlex::Filter.eq("tier", "gold")), # -> "customer.tier"
13
+ # Backlex::Filter.gte("placed_at", Backlex::Filter.now(sub: { "months" => 1 })),
14
+ # ))
15
+ # .select("id", "total", "customer.name")
16
+ # .order_by("-placed_at", "id")
17
+ # .limit(50)
18
+ # .list
19
+ module Filter
20
+ module_function
21
+
22
+ def leaf(field, op, value)
23
+ { field => { op => value } }
24
+ end
25
+
26
+ def eq(f, v); leaf(f, "_eq", v); end
27
+ def neq(f, v); leaf(f, "_neq", v); end
28
+ def gt(f, v); leaf(f, "_gt", v); end
29
+ def gte(f, v); leaf(f, "_gte", v); end
30
+ def lt(f, v); leaf(f, "_lt", v); end
31
+ def lte(f, v); leaf(f, "_lte", v); end
32
+ def in_(f, vs); leaf(f, "_in", vs); end
33
+ def nin(f, vs); leaf(f, "_nin", vs); end
34
+ def between(f, lo, hi); leaf(f, "_between", [lo, hi]); end
35
+ def is_null(f, is_null = true); leaf(f, "_null", is_null); end
36
+ def empty(f); leaf(f, "_empty", true); end
37
+ def nempty(f); leaf(f, "_nempty", true); end
38
+ def contains(f, v); leaf(f, "_contains", v); end
39
+ def icontains(f, v); leaf(f, "_icontains", v); end
40
+ def starts_with(f, v); leaf(f, "_starts_with", v); end
41
+ def ends_with(f, v); leaf(f, "_ends_with", v); end
42
+
43
+ def and_(*conds); { "$and" => conds }; end
44
+ def or_(*conds); { "$or" => conds }; end
45
+ def not_(cond); { "$not" => cond }; end
46
+
47
+ # Traverse a relation one hop: every leaf key produced by +conds+ is prefixed
48
+ # with "head.". Multiple conds are ANDed first.
49
+ def rel(head, *conds)
50
+ inner = conds.length == 1 ? conds[0] : { "$and" => conds }
51
+ prefix_keys(inner, head)
52
+ end
53
+
54
+ # Relative-date value, e.g. Filter.now(sub: { "months" => 1 }).
55
+ def now(add: nil, sub: nil)
56
+ opts = {}
57
+ opts["add"] = add if add
58
+ opts["sub"] = sub if sub
59
+ { "$now" => opts }
60
+ end
61
+
62
+ def prefix_keys(cond, head)
63
+ return { "$and" => cond["$and"].map { |c| prefix_keys(c, head) } } if cond["$and"].is_a?(Array)
64
+ return { "$or" => cond["$or"].map { |c| prefix_keys(c, head) } } if cond["$or"].is_a?(Array)
65
+ return { "$not" => prefix_keys(cond["$not"], head) } if cond["$not"].is_a?(Hash)
66
+
67
+ out = {}
68
+ cond.each { |k, v| out["#{head}.#{k}"] = v }
69
+ out
70
+ end
71
+
72
+ # Turn any accepted filter shape into the canonical Condition: handles
73
+ # $and/$or/$not (and their _ aliases) and implicit equality
74
+ # ({ "status" => "active" } -> { "status" => { "_eq" => "active" } }). Idempotent.
75
+ def normalize(raw)
76
+ return {} unless raw.is_a?(Hash)
77
+
78
+ a = raw["$and"] || raw["_and"]
79
+ return { "$and" => a.map { |c| normalize(c) } } if a.is_a?(Array)
80
+
81
+ o = raw["$or"] || raw["_or"]
82
+ return { "$or" => o.map { |c| normalize(c) } } if o.is_a?(Array)
83
+
84
+ if raw.key?("$not") || raw.key?("_not")
85
+ return { "$not" => normalize(raw["$not"] || raw["_not"]) }
86
+ end
87
+
88
+ out = {}
89
+ raw.each do |k, v|
90
+ out[k] =
91
+ if v.is_a?(Hash) && comparison?(v) then v
92
+ elsif v.is_a?(Hash) then v # unknown object shape — pass through
93
+ else { "_eq" => v }
94
+ end
95
+ end
96
+ out
97
+ end
98
+
99
+ def comparison?(hash)
100
+ !hash.empty? && hash.keys.all? { |k| k.to_s.start_with?("_") }
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Backlex
4
+ # Chainable builder that compiles to a ListQuery hash and runs it.
5
+ class QueryBuilder
6
+ def initialize(list_fn)
7
+ @list_fn = list_fn
8
+ @q = { filter: nil, sort: [], fields: [], expand: [], limit: nil, offset: nil, meta: nil, locale: nil, q: nil }
9
+ end
10
+
11
+ def where(cond)
12
+ @q[:filter] = Filter.normalize(cond)
13
+ self
14
+ end
15
+
16
+ # Replace the filter with a raw canonical condition (escape hatch).
17
+ def filter(cond)
18
+ @q[:filter] = Filter.normalize(cond)
19
+ self
20
+ end
21
+
22
+ def select(*fields)
23
+ @q[:fields].concat(fields)
24
+ self
25
+ end
26
+
27
+ def order_by(*sorts)
28
+ @q[:sort].concat(sorts)
29
+ self
30
+ end
31
+
32
+ # Inline single-hop relations (replaces each FK with the related object).
33
+ def expand(*rels)
34
+ @q[:expand].concat(rels)
35
+ self
36
+ end
37
+
38
+ # Project i18n_text fields to one locale, or "*" for the full map.
39
+ def locale(loc)
40
+ @q[:locale] = loc
41
+ self
42
+ end
43
+
44
+ # Free-text search across readable text fields.
45
+ def search(text)
46
+ @q[:q] = text
47
+ self
48
+ end
49
+
50
+ def limit(n)
51
+ @q[:limit] = n
52
+ self
53
+ end
54
+
55
+ def offset(n)
56
+ @q[:offset] = n
57
+ self
58
+ end
59
+
60
+ # Request an extra COUNT: "filter_count", "total_count", or "*".
61
+ def with_meta(m)
62
+ @q[:meta] = m
63
+ self
64
+ end
65
+
66
+ # The assembled ListQuery hash — the canonical input the API takes.
67
+ def to_query
68
+ @q
69
+ end
70
+
71
+ def list
72
+ @list_fn.call(@q)
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module Backlex
8
+ # Handle for an active realtime subscription. #close unsubscribes — the same
9
+ # contract as the TS SDK's returned unsubscribe function. The reader runs on a
10
+ # background thread and auto-reconnects on a dropped stream (3s back-off),
11
+ # replaying via Last-Event-ID.
12
+ class Subscription
13
+ def initialize(client, url, on_event, on_error)
14
+ @stopped = false
15
+ @thread = Thread.new { run(client, url, on_event, on_error) }
16
+ end
17
+
18
+ def close
19
+ @stopped = true
20
+ @thread&.kill
21
+ end
22
+
23
+ private
24
+
25
+ def run(client, url, on_event, on_error)
26
+ last_id = nil
27
+ until @stopped
28
+ begin
29
+ uri = URI(url)
30
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
31
+ req = Net::HTTP::Get.new(uri)
32
+ req["Accept"] = "text/event-stream"
33
+ client.auth_header(req)
34
+ req["Last-Event-ID"] = last_id if last_id
35
+ http.request(req) do |res|
36
+ if res.code.to_i != 200
37
+ on_error&.call(Backlex::Error.new(res.code.to_i, "UNKNOWN", "HTTP #{res.code}"))
38
+ next
39
+ end
40
+ last_id = read_stream(res, on_event, on_error, last_id)
41
+ end
42
+ end
43
+ rescue StandardError => e
44
+ on_error&.call(e) unless @stopped
45
+ end
46
+ break if @stopped
47
+
48
+ sleep 3
49
+ end
50
+ end
51
+
52
+ # Parse the SSE byte stream, buffering across chunk boundaries.
53
+ def read_stream(res, on_event, on_error, last_id)
54
+ buffer = +""
55
+ data = []
56
+ res.read_body do |chunk|
57
+ break if @stopped
58
+
59
+ buffer << chunk
60
+ while (idx = buffer.index("\n"))
61
+ line = buffer.slice!(0, idx + 1).chomp
62
+ if line.empty?
63
+ unless data.empty?
64
+ payload = data.join("\n")
65
+ data = []
66
+ begin
67
+ on_event.call(JSON.parse(payload))
68
+ rescue StandardError => e
69
+ on_error&.call(e)
70
+ end
71
+ end
72
+ elsif line.start_with?(":")
73
+ # comment / heartbeat
74
+ elsif line.start_with?("id:")
75
+ last_id = line[3..].strip
76
+ elsif line.start_with?("data:")
77
+ d = line[5..]
78
+ d = d[1..] if d.start_with?(" ")
79
+ data << d
80
+ end
81
+ end
82
+ end
83
+ last_id
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Backlex
6
+ # File operations against /api/storage.
7
+ class Storage
8
+ def initialize(client)
9
+ @client = client
10
+ end
11
+
12
+ # List stored objects, optionally filtered by key prefix.
13
+ def list(prefix = nil)
14
+ path = "/api/storage"
15
+ path += "?prefix=#{URI.encode_www_form_component(prefix)}" if prefix && !prefix.empty?
16
+ @client.request("GET", path)["data"]
17
+ end
18
+
19
+ # Upload bytes under +key+. Pass content_type/folder_id nil to omit them.
20
+ def put(key, body, content_type: nil, folder_id: nil)
21
+ path = "/api/storage/#{URI.encode_www_form_component(key)}"
22
+ path += "?folderId=#{URI.encode_www_form_component(folder_id)}" if folder_id
23
+ @client.put_raw(path, body, content_type)
24
+ end
25
+
26
+ # Fetch the raw bytes for +key+.
27
+ def download(key)
28
+ @client.get_raw("/api/storage/#{URI.encode_www_form_component(key)}")
29
+ end
30
+
31
+ # Remove the object at +key+.
32
+ def delete(key)
33
+ @client.request("DELETE", "/api/storage/#{URI.encode_www_form_component(key)}")
34
+ end
35
+ end
36
+ end
data/lib/backlex.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Official Ruby client for the backlex API.
4
+ #
5
+ # require "backlex"
6
+ # client = Backlex::Client.new("https://api.example.com", api_key: "pak_...")
7
+ # posts = client.from("posts").query.where(Backlex::Filter.eq("published", true)).list
8
+ module Backlex
9
+ VERSION = "0.0.1"
10
+ end
11
+
12
+ require_relative "backlex/error"
13
+ require_relative "backlex/filter"
14
+ require_relative "backlex/query_builder"
15
+ require_relative "backlex/collection"
16
+ require_relative "backlex/auth"
17
+ require_relative "backlex/storage"
18
+ require_relative "backlex/realtime"
19
+ require_relative "backlex/client"
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: backlex
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - backlex
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-06-17 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A thin, typed wrapper over the backlex REST + SSE API. Zero runtime dependencies
14
+ (stdlib net/http + json).
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/backlex.rb
23
+ - lib/backlex/auth.rb
24
+ - lib/backlex/client.rb
25
+ - lib/backlex/collection.rb
26
+ - lib/backlex/error.rb
27
+ - lib/backlex/filter.rb
28
+ - lib/backlex/query_builder.rb
29
+ - lib/backlex/realtime.rb
30
+ - lib/backlex/storage.rb
31
+ homepage: https://backlex.com
32
+ licenses:
33
+ - Apache-2.0
34
+ metadata:
35
+ documentation_uri: https://backlex.com/docs/client-sdks
36
+ source_code_uri: https://github.com/backlex/backlex
37
+ post_install_message:
38
+ rdoc_options: []
39
+ require_paths:
40
+ - lib
41
+ required_ruby_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: '2.6'
46
+ required_rubygems_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: '0'
51
+ requirements: []
52
+ rubygems_version: 3.0.3.1
53
+ signing_key:
54
+ specification_version: 4
55
+ summary: Official Ruby client for the backlex API (CRUD, query builder, auth, realtime,
56
+ storage).
57
+ test_files: []