@gusto/baerly-storage 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.
- package/README.md +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
package/dist/API.md
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: baerly-storage — public API quickref
|
|
3
|
+
audience: agent
|
|
4
|
+
summary: One-read flat reference of the public API surface for headless / CLI agents without a TypeScript language server.
|
|
5
|
+
tags: [agent-quickref, baerly]
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# baerly-storage — public API quickref
|
|
9
|
+
|
|
10
|
+
This file ships in `dist/API.md` so a freshly-installed
|
|
11
|
+
`node_modules/@gusto/baerly-storage/dist/API.md` is one `cat` away from the
|
|
12
|
+
full public surface. (It is named `API.md` rather than `AGENTS.md` to
|
|
13
|
+
avoid colliding with the scaffolded user app's own `AGENTS.md` at the
|
|
14
|
+
project root.) It is hand-curated; the `.d.ts` files in this same
|
|
15
|
+
directory remain the source of truth (the bundler chunks them across
|
|
16
|
+
`index-*.d.ts` / `client-*.d.ts` / `db-*.d.ts` / etc., so they're
|
|
17
|
+
noisy to read flat — read this first, drop into the `.d.ts` chunks
|
|
18
|
+
only for exact signatures).
|
|
19
|
+
|
|
20
|
+
## Imports cheat sheet
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// Server kernel
|
|
24
|
+
import {
|
|
25
|
+
Db,
|
|
26
|
+
MemoryStorage, // in-memory `Storage`; canonical for tests
|
|
27
|
+
type Collection, type Query,
|
|
28
|
+
type DocumentData,
|
|
29
|
+
BaerlyError, type BaerlyErrorCode,
|
|
30
|
+
defineConfig, // narrower; root barrel
|
|
31
|
+
} from "@gusto/baerly-storage";
|
|
32
|
+
|
|
33
|
+
// Scaffold-aware config (`app`, `tenant`, `target`, `domain`, …)
|
|
34
|
+
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
35
|
+
// → use this one inside `baerly.config.ts`.
|
|
36
|
+
|
|
37
|
+
// Browser / Node client (HTTP)
|
|
38
|
+
import {
|
|
39
|
+
createBaerlyClient,
|
|
40
|
+
type BaerlyClient, type ClientCollection, type ClientQuery,
|
|
41
|
+
type TerminalOptions, type Fetcher,
|
|
42
|
+
} from "@gusto/baerly-storage/client";
|
|
43
|
+
|
|
44
|
+
// Auth verifiers
|
|
45
|
+
import {
|
|
46
|
+
sharedSecret, cloudflareAccess, bearerJwt,
|
|
47
|
+
} from "@gusto/baerly-storage/auth";
|
|
48
|
+
|
|
49
|
+
// Adapters
|
|
50
|
+
import { baerlyWorker, r2BindingStorage } from "@gusto/baerly-storage/cloudflare";
|
|
51
|
+
import { baerlyNode, s3Storage, r2Storage, minioStorage, gcsStorage } from "@gusto/baerly-storage/node";
|
|
52
|
+
|
|
53
|
+
// Dev helpers (Vite, local-fs storage)
|
|
54
|
+
import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
|
|
55
|
+
import { LocalFsStorage } from "@gusto/baerly-storage/dev";
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## `Db.create({ storage, app, tenant, config? })`
|
|
59
|
+
|
|
60
|
+
One `Db` per `(app, tenant)` request. The constructor is private —
|
|
61
|
+
always go through `Db.create`. Collections are auto-provisioned on first
|
|
62
|
+
write (no `ensureCollection` step).
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { Db, MemoryStorage } from "@gusto/baerly-storage";
|
|
66
|
+
import config from "./baerly.config";
|
|
67
|
+
|
|
68
|
+
const db = Db.create({
|
|
69
|
+
storage: new MemoryStorage(), // or `s3Storage(...)`, `r2BindingStorage(env.BUCKET)`, …
|
|
70
|
+
app: "tickets",
|
|
71
|
+
tenant: "acme-co",
|
|
72
|
+
config, // ← optional. Wires schemas + indexes
|
|
73
|
+
// AND narrows `db.collection(name)` types.
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
await db.collection("tickets").insert({ title: "first ticket", status: "open" });
|
|
77
|
+
const open = await db.collection("tickets").where({ status: "open" }).all();
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Full `Db.create` config:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
Db.create<TConfig>({
|
|
84
|
+
storage: Storage; // required
|
|
85
|
+
app: string; // required
|
|
86
|
+
tenant: string; // required
|
|
87
|
+
config?: TConfig; // optional; from `defineConfig(...)`
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## `db.collection(name)` → `Collection<T>`
|
|
92
|
+
|
|
93
|
+
`Collection<T>` carries the common-case verbs directly (collection-level
|
|
94
|
+
reads plus by-primary-key mutations). Modifiers (`where`, `order`,
|
|
95
|
+
`limit`) return a `Query<T>` for bulk-by-predicate work. Terminals fire
|
|
96
|
+
I/O on the spot.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
interface Collection<T extends DocumentData = DocumentData> {
|
|
100
|
+
readonly name: string;
|
|
101
|
+
// Reads — whole collection / by id.
|
|
102
|
+
first(): Promise<T | undefined>;
|
|
103
|
+
all(): Promise<T[]>;
|
|
104
|
+
count(): Promise<number>;
|
|
105
|
+
get(id: string): Promise<T | undefined>;
|
|
106
|
+
// Modifiers — return Query<T>.
|
|
107
|
+
where(predicate: PredicateArg<T>): Query<T>; // PredicateArg = Predicate<T> | (q => PredicateBuilder<T>)
|
|
108
|
+
order(spec: OrderSpec<T>): Query<T>;
|
|
109
|
+
limit(n: number): Query<T>;
|
|
110
|
+
// Writes — by primary key.
|
|
111
|
+
insert(doc: Partial<T> & DocumentData): Promise<{ _id: string }>;
|
|
112
|
+
update(id: string, patch: Partial<T>): Promise<{ modified: number }>;
|
|
113
|
+
replace(id: string, doc: T): Promise<void>;
|
|
114
|
+
delete(id: string): Promise<{ deleted: number }>;
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`Query<T>` keeps the chainable read terminals and the predicate-aware
|
|
119
|
+
bulk mutation verbs:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
interface Query<T> extends /* Collection<T>'s modifiers */ {
|
|
123
|
+
first(): Promise<T | undefined>;
|
|
124
|
+
all(): Promise<T[]>;
|
|
125
|
+
count(): Promise<number>;
|
|
126
|
+
update(patch: Partial<T>): Promise<{ modified: number }>; // bulk
|
|
127
|
+
delete(): Promise<{ deleted: number }>; // bulk
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`replace` is by-id only — `Collection<T>.replace(id, doc)` throws
|
|
132
|
+
`NotFound` on missing id. There is no predicate-form `.replace(doc)`
|
|
133
|
+
on `Query<T>`: a strict-cardinality-1 verb is redundant ceremony to
|
|
134
|
+
the by-id form (see ADR-002).
|
|
135
|
+
|
|
136
|
+
### Predicates
|
|
137
|
+
|
|
138
|
+
Two shapes, both legal on `.where(...)`:
|
|
139
|
+
|
|
140
|
+
1. **Object literal** — equality only. Top-level, dotted-path, or
|
|
141
|
+
nested literal sub-predicate. Multi-field is implicit AND.
|
|
142
|
+
2. **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`.
|
|
143
|
+
The methods on `PredicateBuilder<T>` ARE the supported operator
|
|
144
|
+
vocabulary; methods absent from the type (`or`, `not`, `regex`,
|
|
145
|
+
`ne`, `exists`) do not exist and won't typecheck.
|
|
146
|
+
|
|
147
|
+
Chained `.where(...).where(...)` AND-merges across calls and across
|
|
148
|
+
shapes. Both forms normalise to one wire format (a flat clause list,
|
|
149
|
+
`{ clauses: PredicateClause[] }`); the HTTP `?where=` param carries
|
|
150
|
+
that wire JSON.
|
|
151
|
+
|
|
152
|
+
By-`_id` lookups go through `.get(id)` / `.update(id, patch)` /
|
|
153
|
+
`.replace(id, doc)` / `.delete(id)`, **not** `.where({ _id: id })`.
|
|
154
|
+
`_id` is excluded from `Path<T>` (and so from `PredicateBuilder<T>`),
|
|
155
|
+
so `.where({ _id: ... })` is a compile-time TS error. Nested `_id`
|
|
156
|
+
paths (`author._id`) on referenced documents are still allowed.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
db.collection("tickets").where({ status: "open" }).all();
|
|
160
|
+
db.collection("tickets").where({ "assignee.team": "platform" }).all();
|
|
161
|
+
db.collection("tickets").where(q => q.gte("count", 1).lt("count", 10)).all();
|
|
162
|
+
db.collection("tickets").where(q => q.in("status", ["open", "pending"])).all();
|
|
163
|
+
db.collection("tickets")
|
|
164
|
+
.where({ status: "open" })
|
|
165
|
+
.where(q => q.gte("priority", 5))
|
|
166
|
+
.all();
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### Wire format (`?where=`)
|
|
170
|
+
|
|
171
|
+
`PredicateWire` is the on-the-wire shape:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
interface PredicateClause {
|
|
175
|
+
readonly op: "eq" | "gt" | "gte" | "lt" | "lte" | "in";
|
|
176
|
+
readonly field: string; // top-level or dotted path
|
|
177
|
+
readonly value: DocumentValue | ReadonlyArray<DocumentValue>; // array iff op === "in"
|
|
178
|
+
}
|
|
179
|
+
interface PredicateWire { readonly clauses: ReadonlyArray<PredicateClause>; }
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Example: `.where({ status: "open" })` → `{"clauses":[{"op":"eq","field":"status","value":"open"}]}`.
|
|
183
|
+
The empty wire `{"clauses":[]}` matches every document.
|
|
184
|
+
|
|
185
|
+
## Mutations
|
|
186
|
+
|
|
187
|
+
By-id (the common case) lives on `Collection<T>`; predicate-aware bulk
|
|
188
|
+
verbs live on `Query<T>` after `.where(...)`.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
await db.collection("tickets").insert({ status: "open", title: "ship it" });
|
|
192
|
+
// → { _id: "01HQ..." } (UUIDv7; caller may supply `_id`)
|
|
193
|
+
|
|
194
|
+
// By-id (Collection<T>):
|
|
195
|
+
await db.collection("tickets").update("01HQ...", { status: "closed" });
|
|
196
|
+
// → { modified: 1 } (JSON-merge-patch RFC 7386; `null` deletes a field)
|
|
197
|
+
|
|
198
|
+
await db.collection("tickets").replace("01HQ...", {
|
|
199
|
+
_id: "01HQ...", status: "open", title: "rewrite",
|
|
200
|
+
});
|
|
201
|
+
// → void (whole-document overwrite)
|
|
202
|
+
|
|
203
|
+
await db.collection("tickets").delete("01HQ...");
|
|
204
|
+
// → { deleted: 1 } (or `{ deleted: 0 }` if the id is unknown)
|
|
205
|
+
|
|
206
|
+
// Bulk-by-predicate (Query<T>):
|
|
207
|
+
await db.collection("tickets")
|
|
208
|
+
.where({ status: "open" })
|
|
209
|
+
.update({ status: "closed", closed_at: new Date().toISOString() });
|
|
210
|
+
// → { modified: N }
|
|
211
|
+
|
|
212
|
+
await db.collection("tickets").where({ status: "closed" }).delete();
|
|
213
|
+
// → { deleted: N }
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## `DocumentData` — row shape constraint
|
|
217
|
+
|
|
218
|
+
Every row type must satisfy
|
|
219
|
+
`{ [k: string]: DocumentValue }` where
|
|
220
|
+
`DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>`.
|
|
221
|
+
|
|
222
|
+
Note: `null` is intentionally NOT a valid stored value. In a
|
|
223
|
+
JSON-merge-patch (RFC 7386) `update`, `null` is the field-deletion
|
|
224
|
+
sentinel; allowing it as a stored value would collapse "this field is
|
|
225
|
+
null" with "delete this field". Use `.optional()` in your schema for
|
|
226
|
+
absent values.
|
|
227
|
+
|
|
228
|
+
Two ways to get a typed row:
|
|
229
|
+
|
|
230
|
+
1. **Bind the config** (preferred). Declare collection in
|
|
231
|
+
`baerly.config.ts` with a schema; pass `config` to `Db.create` /
|
|
232
|
+
`createBaerlyClient`. `db.collection("tickets")` returns
|
|
233
|
+
`Collection<RowOf<TConfig, "tickets">>`. No generic, no cast.
|
|
234
|
+
|
|
235
|
+
2. **Falls back to `DocumentData`** when no config is bound. Cast at
|
|
236
|
+
the construction site for a narrower row shape:
|
|
237
|
+
```ts
|
|
238
|
+
import type { Collection, DocumentData } from "@gusto/baerly-storage";
|
|
239
|
+
interface Bookmark extends DocumentData { _id: string; url: string }
|
|
240
|
+
const bookmarks = db.collection("bookmarks") as Collection<Bookmark>;
|
|
241
|
+
await bookmarks.all();
|
|
242
|
+
```
|
|
243
|
+
A plain `interface Bookmark { _id: string; url: string }` (no
|
|
244
|
+
index signature) fails the `T extends DocumentData` constraint by
|
|
245
|
+
design — the constraint keeps the row JSON-compatible.
|
|
246
|
+
|
|
247
|
+
## Errors
|
|
248
|
+
|
|
249
|
+
`BaerlyError` is the single error class. Discriminate by `code`, not
|
|
250
|
+
`instanceof` (the code string survives realm boundaries):
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
try {
|
|
254
|
+
await db.collection("tickets").insert({ title: "hi" });
|
|
255
|
+
} catch (err) {
|
|
256
|
+
if (err instanceof BaerlyError && err.code === "Conflict") {
|
|
257
|
+
// CAS lost; caller decides whether to retry
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
| `code` | HTTP | When |
|
|
263
|
+
| ------------------------ | ---- | -------------------------------------------------------------------- |
|
|
264
|
+
| `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …) |
|
|
265
|
+
| `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
|
|
266
|
+
| `AccessDenied` | 403 | S3 403 or bucket policy denied |
|
|
267
|
+
| `InvalidResponse` | 502 | Server returned unparseable body |
|
|
268
|
+
| `Internal` | 500 | Invariant violation — file a bug |
|
|
269
|
+
| `SchemaError` | 422 | JSON shape invalid or bound schema rejected the doc |
|
|
270
|
+
| `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision |
|
|
271
|
+
| `Unauthorized` | 401 | Verifier returned no identity |
|
|
272
|
+
| `NotFound` | 404 | Row by id not found |
|
|
273
|
+
| `PayloadTooLarge` | 413 | Body > 1 MiB cap |
|
|
274
|
+
| `UnsatisfiablePredicate` | 400 | Predicate is well-formed but contradicts itself (empty `in` set, etc.) |
|
|
275
|
+
|
|
276
|
+
## `defineConfig({ app, tenant, target, collections })`
|
|
277
|
+
|
|
278
|
+
Scaffold-aware: lives at `@gusto/baerly-storage/config`. Holds both deploy
|
|
279
|
+
metadata (`app`, `tenant`, `target`, `domain`, `cloudflareAccess`,
|
|
280
|
+
`requiredSecrets`, `observability`) AND the runtime schema map.
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
284
|
+
import { z } from "zod";
|
|
285
|
+
|
|
286
|
+
const TicketSchema = z.object({
|
|
287
|
+
_id: z.string().optional(),
|
|
288
|
+
status: z.enum(["open", "closed"]),
|
|
289
|
+
title: z.string().min(1),
|
|
290
|
+
tags: z.array(z.string()).optional(),
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
export default defineConfig({
|
|
294
|
+
app: "helpdesk",
|
|
295
|
+
tenant: "acme",
|
|
296
|
+
target: "cloudflare",
|
|
297
|
+
collections: {
|
|
298
|
+
tickets: {
|
|
299
|
+
schema: TicketSchema, // StandardSchema v1
|
|
300
|
+
indexes: [{ name: "by_status", on: "status" }], // single-field equality
|
|
301
|
+
},
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Schemas: any [StandardSchema v1](https://standardschema.dev) validator
|
|
307
|
+
(Zod 3.24+, Valibot 0.36+, ArkType 2.0+). Validation runs on the
|
|
308
|
+
post-image: `update` and `replace` see the full doc, not just the
|
|
309
|
+
patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`,
|
|
310
|
+
mapped to HTTP 422.
|
|
311
|
+
|
|
312
|
+
Indexes: declared here, threaded into `Db.create` automatically. The
|
|
313
|
+
read-path auto-planner picks an index when the predicate matches;
|
|
314
|
+
mismatches fall back to the full scan with a metric bump (correctness
|
|
315
|
+
preserved).
|
|
316
|
+
|
|
317
|
+
## `createBaerlyClient` (browser / Node HTTP client)
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import type config from "./baerly.config"; // type-only — server adapter stays out of the SPA bundle
|
|
321
|
+
const client = createBaerlyClient<typeof config>({
|
|
322
|
+
baseUrl: "", // same-origin
|
|
323
|
+
headers: { Authorization: "Bearer …" }, // wrap `fetch` for per-call refresh
|
|
324
|
+
fetch: customFetcher, // optional Fetcher middleware
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
await client.collection("tickets").where({ status: "open" }).all();
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
`ClientCollection<T>` mirrors `Collection<T>` but every terminal accepts a
|
|
331
|
+
trailing `TerminalOptions`:
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
interface TerminalOptions {
|
|
335
|
+
signal?: AbortSignal; // cancels this specific request
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
await client.collection("tickets").all({ signal: ac.signal });
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
That extra options bag is the **only** API difference between
|
|
342
|
+
`Collection<T>` and `ClientCollection<T>`. Same modifiers, same terminals,
|
|
343
|
+
same predicates.
|
|
344
|
+
|
|
345
|
+
## Long-poll: `/v1/since`
|
|
346
|
+
|
|
347
|
+
`GET /v1/since?collection=…&cursor=…` is the long-poll endpoint that
|
|
348
|
+
streams mutations without WebSockets. The server holds the request
|
|
349
|
+
open for ~25 s; if new log entries land in that window it flushes
|
|
350
|
+
them immediately, otherwise it returns an empty batch with the
|
|
351
|
+
cursor unchanged.
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
// Wire shape (returned raw — not wrapped in HttpOkEnvelope):
|
|
355
|
+
interface SinceResponse {
|
|
356
|
+
readonly events: ReadonlyArray<LogEntry>;
|
|
357
|
+
readonly next_cursor: string;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
interface LogEntry {
|
|
361
|
+
readonly lsn: string; // opaque cursor; lex-asc, monotonic
|
|
362
|
+
readonly commit_ts: string; // ISO-8601 ms
|
|
363
|
+
readonly op: "I" | "U" | "D" | "T" | "M";
|
|
364
|
+
readonly collection: string;
|
|
365
|
+
readonly doc_id?: string; // I/U/D only
|
|
366
|
+
readonly new?: DocumentData; // I/U — post-image
|
|
367
|
+
readonly patch?: DocumentData; // U — JSON-merge-patch (RFC 7386)
|
|
368
|
+
readonly schema_version: number;
|
|
369
|
+
readonly session: string;
|
|
370
|
+
readonly seq: number;
|
|
371
|
+
// `old` / `key_old` / `origin` are optional; see `LogEntry` JSDoc.
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
**Cursor priming.** First call: pass `cursor=` (empty string). The
|
|
376
|
+
server's fast path returns immediately *iff* the log already has
|
|
377
|
+
entries for this collection — you get `events: [...]` and the
|
|
378
|
+
last entry's `lsn` as `next_cursor`. **If the collection is empty,
|
|
379
|
+
the first call blocks for the full long-poll budget (~25 s) before
|
|
380
|
+
returning `events: []` with `next_cursor: ''`.** Either prime by
|
|
381
|
+
inserting one row first if you need an immediate response, or budget
|
|
382
|
+
your client / test for the full timeout. Subsequent calls pass the
|
|
383
|
+
returned cursor back — the cursor is opaque, treat it as a string,
|
|
384
|
+
and `events` is empty iff the budget elapsed with no new writes
|
|
385
|
+
(`next_cursor` unchanged).
|
|
386
|
+
|
|
387
|
+
**Test-mode tuning.** Vitest's default per-test timeout is 5 s; the
|
|
388
|
+
long-poll's 25 s budget will dominate that. Shrink it on the worker
|
|
389
|
+
factory under a test-only env switch:
|
|
390
|
+
|
|
391
|
+
```ts
|
|
392
|
+
export default baerlyWorker((env) => ({
|
|
393
|
+
config,
|
|
394
|
+
// Production: omit both (inherit 25 s / 1 s defaults).
|
|
395
|
+
// Test: wire from miniflare bindings.
|
|
396
|
+
sinceTimeoutMs: env.SINCE_TIMEOUT_MS,
|
|
397
|
+
sincePollIntervalMs: env.SINCE_POLL_INTERVAL_MS,
|
|
398
|
+
}));
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
In `vitest.config.mts`'s miniflare bindings, set them as numbers
|
|
402
|
+
(`SINCE_TIMEOUT_MS: 2000`, `SINCE_POLL_INTERVAL_MS: 50`) so the
|
|
403
|
+
factory sees `number | undefined` without runtime coercion. Don't
|
|
404
|
+
shrink `sinceTimeoutMs` in production code paths — it multiplies the
|
|
405
|
+
R2 class-A op count per idle long-poll connection.
|
|
406
|
+
|
|
407
|
+
React applications use `@gusto/baerly-storage/client/react` (see next
|
|
408
|
+
section) instead of poking `/v1/since` by hand; hand-rolled
|
|
409
|
+
subscribers in other UI frameworks can `fetch` this endpoint
|
|
410
|
+
directly, or import the internal `pollSinceOnce` helper from
|
|
411
|
+
`@baerly/client` if cursor-aware tailing is needed.
|
|
412
|
+
|
|
413
|
+
## React: `BaerlyProvider`, `useQuery`, `useMutation`
|
|
414
|
+
|
|
415
|
+
`@gusto/baerly-storage/client/react` exposes three symbols. The provider
|
|
416
|
+
owns a shared `/v1/since` long-poll per `(client, collection)`; idle
|
|
417
|
+
cycles cost zero list reads, and any non-empty batch invalidates
|
|
418
|
+
every `useQuery` whose chain touches the firing collection.
|
|
419
|
+
|
|
420
|
+
```tsx
|
|
421
|
+
import {
|
|
422
|
+
BaerlyProvider, useQuery, useMutation,
|
|
423
|
+
} from "@gusto/baerly-storage/client/react";
|
|
424
|
+
|
|
425
|
+
// 1. Wrap your app once.
|
|
426
|
+
<BaerlyProvider client={createBaerlyClient({ baseUrl: "", config })}>
|
|
427
|
+
<App />
|
|
428
|
+
</BaerlyProvider>
|
|
429
|
+
|
|
430
|
+
// 2. useQuery(cb, deps) — cb receives the bare client and returns
|
|
431
|
+
// a ClientCollection / ClientQuery chain. Re-runs on deps change OR
|
|
432
|
+
// on long-poll invalidation. Result is a discriminated union:
|
|
433
|
+
const result = useQuery((c) => c.collection("notes").all() as Promise<Note[]>, []);
|
|
434
|
+
// result.status: "loading" | "ok" | "error" | "skipped"
|
|
435
|
+
// result.data: T[] | undefined (present iff status === "ok")
|
|
436
|
+
// result.error: BaerlyError | undefined (present iff status === "error")
|
|
437
|
+
|
|
438
|
+
// 3. useQuery.skip — short-circuit to status: "skipped", no
|
|
439
|
+
// subscription. Use for conditional or dependent reads.
|
|
440
|
+
const filtered = useQuery(
|
|
441
|
+
(c) => filter === "all"
|
|
442
|
+
? useQuery.skip
|
|
443
|
+
: c.collection("notes").where({ status: filter }).all() as Promise<Note[]>,
|
|
444
|
+
[filter],
|
|
445
|
+
);
|
|
446
|
+
|
|
447
|
+
// 4. useMutation() — returns [mutate, { isPending, error }].
|
|
448
|
+
// Run any client call inside mutate; subscribed useQuery reads
|
|
449
|
+
// re-run automatically once the long-poll sees the write.
|
|
450
|
+
const [mutate, { isPending, error }] = useMutation();
|
|
451
|
+
await mutate((c) => c.collection("notes").insert({ body }));
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
## HTTP wire format
|
|
455
|
+
|
|
456
|
+
The JS SDK is the canonical path. Reach for `curl` only when
|
|
457
|
+
debugging. Mutation bodies are wrapped:
|
|
458
|
+
|
|
459
|
+
| Route | Body | Response |
|
|
460
|
+
| -------------------------------- | ------------------- | ------------------------------ |
|
|
461
|
+
| `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
|
|
462
|
+
| `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
|
|
463
|
+
| `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
|
|
464
|
+
| `DELETE /v1/c/:collection/:id` | — | `204` |
|
|
465
|
+
|
|
466
|
+
Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
|
|
467
|
+
`GET /v1/since?collection=…&cursor=…`) take no body and return
|
|
468
|
+
`{ data, _meta }` or a route-specific envelope. A flat `POST` body
|
|
469
|
+
(no `doc` wrapper) returns
|
|
470
|
+
`400 SchemaError "Request body must be { doc: object }"` — wording is
|
|
471
|
+
locked by `assertJsonBodyField` in the kernel.
|
|
472
|
+
|
|
473
|
+
### Read modifiers (query params)
|
|
474
|
+
|
|
475
|
+
`GET /v1/c/:collection` accepts three JSON-encoded query params; all are
|
|
476
|
+
optional and compose:
|
|
477
|
+
|
|
478
|
+
| Param | Encodes | Wire example |
|
|
479
|
+
| ---------- | -------------------------------------- | -------------------------------------------- |
|
|
480
|
+
| `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
|
|
481
|
+
| `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
|
|
482
|
+
| `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
|
|
483
|
+
|
|
484
|
+
`?order=` and `?where=` are JSON, **not** Rails-style `field:asc` —
|
|
485
|
+
the kernel `JSON.parse`s them and returns `400 SchemaError` on a flat
|
|
486
|
+
string. Always `encodeURIComponent(JSON.stringify(spec))`. The JS SDK
|
|
487
|
+
(`createBaerlyClient`) and the React hooks build these for you; reach
|
|
488
|
+
for raw URLs only when scripting or when porting another framework's
|
|
489
|
+
client.
|
|
490
|
+
|
|
491
|
+
## Adapter factories
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
// Cloudflare Worker entry
|
|
495
|
+
import { baerlyWorker } from "@gusto/baerly-storage/cloudflare";
|
|
496
|
+
export default baerlyWorker((env) => ({
|
|
497
|
+
verifier: cloudflareAccess({ teamDomain, audienceTag }),
|
|
498
|
+
// scheduled?: (controller, env, ctx) => … // opt-in cron handler
|
|
499
|
+
}));
|
|
500
|
+
|
|
501
|
+
// Node listener entry (any host that runs `node server.js`)
|
|
502
|
+
import { baerlyNode, s3Storage } from "@gusto/baerly-storage/node";
|
|
503
|
+
baerlyNode({
|
|
504
|
+
storage: s3Storage({ bucket: "…", credentials: { … } }),
|
|
505
|
+
verifier: bearerJwt({ jwks, issuer, audience }),
|
|
506
|
+
webRoot: "dist/client", // optional SPA static-serve
|
|
507
|
+
maintenance: { collections: ["tickets"], tenants: ["acme"] }, // optional
|
|
508
|
+
}).listen(PORT);
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
**Single-tenant CF Access.** Vanilla CF Access JWTs carry `sub`/`email`
|
|
512
|
+
but no `tenant` claim. Pin the tenant from env instead of a claim:
|
|
513
|
+
`cloudflareAccess({ teamDomain, audienceTag, tenantPrefix: "main" })`.
|
|
514
|
+
Same option is available on `bearerJwt`.
|
|
515
|
+
|
|
516
|
+
**Local dev (`wrangler dev`, no Vite).** Declare `auth: "none"` in
|
|
517
|
+
`baerly.config.ts` for the dev posture — the adapter synthesizes a
|
|
518
|
+
verifier that pins every request to `config.tenant` without consulting
|
|
519
|
+
the `Authorization` header. Swap to `auth: "shared-secret"` (or pass a
|
|
520
|
+
custom `Verifier` on the factory) when you're ready to gate by wire
|
|
521
|
+
credentials. Production CF Worker recipes layer CF Access in front of
|
|
522
|
+
the Worker route; the verifier reads the resulting JWT:
|
|
523
|
+
|
|
524
|
+
```ts
|
|
525
|
+
// baerly.config.ts
|
|
526
|
+
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
527
|
+
export default defineConfig({
|
|
528
|
+
app: "tickets",
|
|
529
|
+
tenant: "main",
|
|
530
|
+
target: "cloudflare",
|
|
531
|
+
auth: "none", // dev only — production swaps to "shared-secret" or a custom Verifier
|
|
532
|
+
collections: { /* … */ },
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
// src/server/index.ts
|
|
536
|
+
import { baerlyWorker } from "@gusto/baerly-storage/cloudflare";
|
|
537
|
+
import config from "../../baerly.config.ts";
|
|
538
|
+
export default baerlyWorker(() => ({ config }));
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
`s3Storage` / `r2Storage` / `minioStorage` / `gcsStorage` from
|
|
543
|
+
`@gusto/baerly-storage/node` are re-exports of one factory family — same
|
|
544
|
+
shape (bucket + credentials), all hide `aws4fetch` / `@xmldom/xmldom`
|
|
545
|
+
behind the package boundary. **Don't confuse them with
|
|
546
|
+
`r2BindingStorage` from `@gusto/baerly-storage/cloudflare`**: that one takes
|
|
547
|
+
the platform-bound `R2Bucket` directly (`r2BindingStorage(env.BUCKET)`)
|
|
548
|
+
and is the only storage factory a Worker should reach for — the
|
|
549
|
+
credential-based factories assume `fetch` + Node TLS, not the Workers
|
|
550
|
+
runtime.
|
|
551
|
+
|
|
552
|
+
### Verifier presets
|
|
553
|
+
|
|
554
|
+
`@gusto/baerly-storage/auth` ships three `Verifier` functions you can pass
|
|
555
|
+
to `baerlyWorker({ verifier })` or `baerlyNode({ verifier })`. Each
|
|
556
|
+
returns `VerifierResult | null` (null = 401 unauth; thrown
|
|
557
|
+
`BaerlyError` = 500 operator fault — the dispatcher splits the
|
|
558
|
+
codes deliberately so on-call paging targets operator faults only).
|
|
559
|
+
|
|
560
|
+
| Preset | Identity source | Tenant derivation |
|
|
561
|
+
| ------------------ | ------------------------------------------------------------------------------- | -------------------------------------------------- |
|
|
562
|
+
| `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
|
|
563
|
+
| `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
|
|
564
|
+
| `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
|
|
565
|
+
|
|
566
|
+
```ts
|
|
567
|
+
import { sharedSecret, bearerJwt, cloudflareAccess } from "@gusto/baerly-storage/auth";
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
**`tenantPrefix:` (on `bearerJwt` and `cloudflareAccess`).** Pins
|
|
571
|
+
every verified request to a fixed tenant, bypassing claim lookup.
|
|
572
|
+
Use this in single-tenant deployments where the IdP doesn't ship a
|
|
573
|
+
tenant claim — the default `tenantClaim: "tenant"` would 401 every
|
|
574
|
+
request because vanilla CF Access JWTs carry only `sub`/`email`.
|
|
575
|
+
Signature, audience, and expiry checks are still enforced; only
|
|
576
|
+
tenant derivation is replaced.
|
|
577
|
+
|
|
578
|
+
**Why a function and not a class?** The source repo's
|
|
579
|
+
`docs/adr/005-verifier-function-shape.md` records the three
|
|
580
|
+
properties the shape upholds and the four rejected alternatives.
|
|
581
|
+
|
|
582
|
+
## Observability
|
|
583
|
+
|
|
584
|
+
`baerlyWorker` and `baerlyNode` emit **one canonical log line per
|
|
585
|
+
HTTP request** on stdout (default level `info`). Background work
|
|
586
|
+
(compactor / GC / `runScheduledMaintenance`) emits a separate
|
|
587
|
+
`unit_of_work: "maintenance"` line per tick. The Cloudflare adapter
|
|
588
|
+
is JSON-only (Workers have no TTY); the Node adapter auto-selects a
|
|
589
|
+
human-readable single-line shape when `process.stdout.isTTY ===
|
|
590
|
+
true`. Sinks plug in via `observability.sink` on the factory
|
|
591
|
+
options.
|
|
592
|
+
|
|
593
|
+
```json
|
|
594
|
+
{
|
|
595
|
+
"timestamp": "2026-05-12T17:42:11.823Z",
|
|
596
|
+
"level": "info",
|
|
597
|
+
"category": "baerly.http",
|
|
598
|
+
"request_id": "0193b0a1-ff7a-7c44-b9d5-c3e91d8f3a01",
|
|
599
|
+
"method": "POST",
|
|
600
|
+
"path": "/v1/c/tickets",
|
|
601
|
+
"status": 200,
|
|
602
|
+
"duration_ms": 14.207,
|
|
603
|
+
"outcome": "ok",
|
|
604
|
+
"db.storage.class_a_ops_total": 3,
|
|
605
|
+
"db.storage.class_b_ops_total": 1,
|
|
606
|
+
"db.write.class_a_ops_per_logical_write_sum": 3
|
|
607
|
+
}
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
### Field reference
|
|
611
|
+
|
|
612
|
+
| Field | Meaning |
|
|
613
|
+
| ------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
614
|
+
| `request_id` | Correlation key. Set from `X-Request-Id` if provided, else minted fresh. |
|
|
615
|
+
| `method` / `path` / `status` | HTTP request line + response code. |
|
|
616
|
+
| `cache_status` | `"hit" \| "miss" \| "bypass"` — Cloudflare adapter only. Node adapter omits. |
|
|
617
|
+
| `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
|
|
618
|
+
| `outcome` | `"read"` (GET <400), `"committed"` (non-GET <400), `"conflict"` (409), or `"error"`. |
|
|
619
|
+
| `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
|
|
620
|
+
| `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
|
|
621
|
+
| `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
|
|
622
|
+
| `db.storage.<op>.duration_ms_sum` / `_count`| Per-call duration histogram. |
|
|
623
|
+
| `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
|
|
624
|
+
| `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
|
|
625
|
+
| `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
|
|
626
|
+
|
|
627
|
+
Class-A / Class-B totals are the load-bearing fields — the cost
|
|
628
|
+
model puts a per-request ceiling on Class-A ops and the canonical
|
|
629
|
+
line is how you verify a deployed service stays under it.
|
|
630
|
+
|
|
631
|
+
### Log levels
|
|
632
|
+
|
|
633
|
+
| Level | What lands |
|
|
634
|
+
| ------- | -------------------------------------------------------------------------------- |
|
|
635
|
+
| `error` | `status >= 500` or an exception was thrown. |
|
|
636
|
+
| `warn` | Adds 4xx canonical lines and explicit `warn` records. |
|
|
637
|
+
| `info` | Default. Adds 2xx canonical lines and lifecycle events. |
|
|
638
|
+
| `debug` | Adds per-storage-op events. **High volume**; off in production. |
|
|
639
|
+
|
|
640
|
+
Set `LOG_LEVEL` env var or the typed `observability.level` factory
|
|
641
|
+
option. Sink wiring (Workers Analytics Engine, OTel, Datadog) lives
|
|
642
|
+
in the source repo's `docs/guide/observability.md`.
|
|
643
|
+
|
|
644
|
+
## Recipe — server-stamped trusted fields
|
|
645
|
+
|
|
646
|
+
Use this shape when a column must come from the verified identity
|
|
647
|
+
rather than the client request body (`sender_sub` on chat messages,
|
|
648
|
+
`owner_id` on user-owned rows, `created_by` on audit logs). The
|
|
649
|
+
HTTP routes `baerlyWorker` mounts under `/v1/c/:collection` accept the
|
|
650
|
+
doc verbatim from the request body — they don't read the verifier
|
|
651
|
+
identity into the row. Stamp it yourself in a custom route, then
|
|
652
|
+
block direct client writes to the same collection so a malicious
|
|
653
|
+
client can't supply the field by hand.
|
|
654
|
+
|
|
655
|
+
```ts
|
|
656
|
+
// src/server/index.ts
|
|
657
|
+
import { Db, type Verifier } from "@gusto/baerly-storage";
|
|
658
|
+
import { baerlyWorker, r2BindingStorage } from "@gusto/baerly-storage/cloudflare";
|
|
659
|
+
import type { BaerlyEnv } from "@gusto/baerly-storage/cloudflare";
|
|
660
|
+
import config from "../../baerly.config.ts";
|
|
661
|
+
|
|
662
|
+
// BaerlyEnv already declares `BUCKET: R2Bucket` and `APP: string`.
|
|
663
|
+
// Extend it with anything else the Worker reads from env.
|
|
664
|
+
|
|
665
|
+
const verifier: Verifier = async (req) => {
|
|
666
|
+
const sub = /* extract from CF Access JWT / cookie / header */;
|
|
667
|
+
if (!sub) return null;
|
|
668
|
+
return { tenantPrefix: config.tenant, identity: { sub } };
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
const inner = baerlyWorker(() => ({ config, verifier }));
|
|
672
|
+
|
|
673
|
+
export default {
|
|
674
|
+
async fetch(req: Request, env: BaerlyEnv, ctx: ExecutionContext) {
|
|
675
|
+
const url = new URL(req.url);
|
|
676
|
+
|
|
677
|
+
// (1) Block client writes to the trusted-stamp collection.
|
|
678
|
+
if (
|
|
679
|
+
url.pathname.startsWith("/v1/c/messages") &&
|
|
680
|
+
req.method !== "GET"
|
|
681
|
+
) {
|
|
682
|
+
return new Response("client writes disabled — POST /api/messages", {
|
|
683
|
+
status: 405,
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// (2) Custom route — re-run verifier, stamp field, insert.
|
|
688
|
+
if (url.pathname === "/api/messages" && req.method === "POST") {
|
|
689
|
+
const verified = await verifier(req);
|
|
690
|
+
if (verified === null) {
|
|
691
|
+
return new Response("unauthorized", { status: 401 });
|
|
692
|
+
}
|
|
693
|
+
const { body } = await req.json<{ body: string }>();
|
|
694
|
+
const db = Db.create({
|
|
695
|
+
storage: r2BindingStorage(env.BUCKET),
|
|
696
|
+
app: env.APP,
|
|
697
|
+
tenant: verified.tenantPrefix,
|
|
698
|
+
config,
|
|
699
|
+
});
|
|
700
|
+
const { _id } = await db.collection("messages").insert({
|
|
701
|
+
body,
|
|
702
|
+
sender_sub: (verified.identity as { sub: string }).sub,
|
|
703
|
+
sent_at: Date.now(),
|
|
704
|
+
});
|
|
705
|
+
return Response.json({ _id }, { status: 201 });
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// (3) Everything else goes through baerlyWorker (reads, /v1/since, etc.).
|
|
709
|
+
return inner.fetch!(req, env, ctx);
|
|
710
|
+
},
|
|
711
|
+
} satisfies ExportedHandler<BaerlyEnv>;
|
|
712
|
+
```
|
|
713
|
+
|
|
714
|
+
The client reads via the normal `GET /v1/c/messages` route and tails
|
|
715
|
+
via `GET /v1/since?collection=messages&cursor=…` — both still served by
|
|
716
|
+
`inner`. Only writes go through `/api/messages`.
|
|
717
|
+
|
|
718
|
+
**Known limitations of this recipe.** The custom-route `Db.create` is
|
|
719
|
+
a second instance — it doesn't share `baerlyWorker`'s
|
|
720
|
+
`observableStorage(...)` wrapping (so custom-route writes don't land
|
|
721
|
+
in the canonical-line storage counters) or the read-cache invalidation
|
|
722
|
+
helper. For pre-launch chat-shape apps this is acceptable; the
|
|
723
|
+
observability gap is being tracked as a follow-up. If you also need
|
|
724
|
+
PATCH/PUT/DELETE on the same collection, repeat steps (1) and (2) for
|
|
725
|
+
each verb.
|
|
726
|
+
|
|
727
|
+
## Recipe — wrapping the client `fetch`
|
|
728
|
+
|
|
729
|
+
`createBaerlyClient({ fetch: customFetcher })` is the one composable
|
|
730
|
+
seam for cross-cutting HTTP concerns. The `Fetcher` type is one
|
|
731
|
+
line:
|
|
732
|
+
|
|
733
|
+
```ts
|
|
734
|
+
import { type Fetcher } from "@gusto/baerly-storage/client";
|
|
735
|
+
// type Fetcher = (req: Request) => Promise<Response>;
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
Wrappers compose as ordinary JavaScript functions: outermost sees
|
|
739
|
+
the request first and the response last; innermost is closest to
|
|
740
|
+
the network. Three recipes cover the common cases.
|
|
741
|
+
|
|
742
|
+
### Hook callbacks (success / error)
|
|
743
|
+
|
|
744
|
+
```ts
|
|
745
|
+
import { createBaerlyClient, type Fetcher } from "@gusto/baerly-storage/client";
|
|
746
|
+
|
|
747
|
+
const withHooks = (next: Fetcher, onSuccess: (req: Request, res: Response) => void, onError: (req: Request, err: unknown) => void): Fetcher =>
|
|
748
|
+
async (req) => {
|
|
749
|
+
try {
|
|
750
|
+
const res = await next(req);
|
|
751
|
+
onSuccess(req, res);
|
|
752
|
+
return res;
|
|
753
|
+
} catch (err) {
|
|
754
|
+
onError(req, err);
|
|
755
|
+
throw err;
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
const client = createBaerlyClient({
|
|
760
|
+
baseUrl: "https://api.example.com",
|
|
761
|
+
fetch: withHooks(globalThis.fetch,
|
|
762
|
+
(req, res) => log.info({ url: req.url, status: res.status }),
|
|
763
|
+
(req, err) => log.error({ url: req.url, err }),
|
|
764
|
+
),
|
|
765
|
+
});
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
`onSuccess` fires for **any** HTTP response that completes — 4xx and
|
|
769
|
+
5xx included, because those are not thrown exceptions. Branch on
|
|
770
|
+
`res.ok` if you want "2xx only."
|
|
771
|
+
|
|
772
|
+
### Retry on transient failures (GET only)
|
|
773
|
+
|
|
774
|
+
```ts
|
|
775
|
+
const withRetry = (next: Fetcher, max = 3, baseMs = 100): Fetcher =>
|
|
776
|
+
async (req) => {
|
|
777
|
+
for (let i = 0; i < max - 1; i++) {
|
|
778
|
+
const res = await next(req.clone());
|
|
779
|
+
if (res.ok || res.status < 500 || req.method !== "GET") return res;
|
|
780
|
+
await new Promise((r) => setTimeout(r, baseMs * (i + 1)));
|
|
781
|
+
}
|
|
782
|
+
return next(req);
|
|
783
|
+
};
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
Only retry idempotent reads. `POST` / `PATCH` / `DELETE` may have
|
|
787
|
+
succeeded on the server even when the client sees a 5xx (commit
|
|
788
|
+
fence then network drop). Writes are CAS-guarded so duplicates
|
|
789
|
+
don't corrupt state — but they may surface as `PreconditionFailed`.
|
|
790
|
+
The `req.clone()` is required because a `Request` body is a
|
|
791
|
+
one-shot stream.
|
|
792
|
+
|
|
793
|
+
### Refresh credentials on 401
|
|
794
|
+
|
|
795
|
+
```ts
|
|
796
|
+
const withAuthRefresh = (next: Fetcher, refresh: () => Promise<string>): Fetcher =>
|
|
797
|
+
async (req) => {
|
|
798
|
+
const res = await next(req.clone());
|
|
799
|
+
if (res.status !== 401) return res;
|
|
800
|
+
const token = await refresh();
|
|
801
|
+
const retried = new Request(req, {
|
|
802
|
+
headers: new Headers({
|
|
803
|
+
...Object.fromEntries(req.headers),
|
|
804
|
+
Authorization: `Bearer ${token}`,
|
|
805
|
+
}),
|
|
806
|
+
});
|
|
807
|
+
return next(retried);
|
|
808
|
+
};
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
If the refreshed call also returns 401, the wrapper returns that
|
|
812
|
+
response unchanged — no second retry, avoiding an infinite refresh
|
|
813
|
+
loop on a stale/revoked token. Wire sign-out / re-auth-prompt into
|
|
814
|
+
the caller, not into this wrapper.
|
|
815
|
+
|
|
816
|
+
### Long-poll calls (`GET /v1/since`)
|
|
817
|
+
|
|
818
|
+
The long-poll path routes through the same `Fetcher`. Retry,
|
|
819
|
+
logging, and auth-refresh wrappers apply uniformly. If a wrapper
|
|
820
|
+
needs to distinguish long-poll from one-shot reads, inspect
|
|
821
|
+
`req.url` for `/v1/since`. Most wrappers don't need to.
|
|
822
|
+
|
|
823
|
+
### Composition order
|
|
824
|
+
|
|
825
|
+
The outer wrapper sees retries — `withRetry(withLogging(fetch))` logs
|
|
826
|
+
each attempt; `withLogging(withRetry(fetch))` logs the final outcome
|
|
827
|
+
once. Pick by what you want to observe.
|
|
828
|
+
|
|
829
|
+
## Anti-patterns
|
|
830
|
+
|
|
831
|
+
- Don't reach into `node_modules/@gusto/baerly-storage/dist/` at runtime —
|
|
832
|
+
consume the published exports.
|
|
833
|
+
- Don't widen branded types (`UUID`, `ContentVersionId`) with
|
|
834
|
+
`as string`. The brand exists to prevent confusion bugs.
|
|
835
|
+
- Don't put `SHARED_SECRET` in the SPA bundle. It's
|
|
836
|
+
server-to-server-only; the dev path uses `baerlyDevAuth` to inject
|
|
837
|
+
it server-side, the prod path uses CF Access (CF target) or
|
|
838
|
+
`bearerJwt` (Node target).
|
|
839
|
+
- Don't mutate `VerifierResult.tenantPrefix` between the verifier
|
|
840
|
+
and `Db.create`. The dispatcher pins the tenant from the
|
|
841
|
+
verifier's return value.
|
|
842
|
+
|
|
843
|
+
## Where to look next
|
|
844
|
+
|
|
845
|
+
- Per-symbol JSDoc: read the `.d.ts` chunks in this directory
|
|
846
|
+
(`db-*.d.ts`, `index-*.d.ts`, `client-*.d.ts`, …) — the bundler
|
|
847
|
+
splits them; `cat dist/*.d.ts` gives the union.
|
|
848
|
+
- Theoretical foundations + cost model: the repository's `docs/`
|
|
849
|
+
tree (`docs/about/`, `docs/spec/`).
|
|
850
|
+
- Recipes: `docs/guide/` (auth, observability, backups, troubleshooting).
|