@gusto/baerly-storage 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/API.md +161 -10
- package/dist/{app-config-Cb5dO2s9.d.ts → app-config-C0Bbw_Z6.d.ts} +18 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-BLf3Ae5s.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-D62JguBc.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-CjUO1Bec.js → http-Cw8p6y5b.js} +8 -8
- package/dist/{http-CjUO1Bec.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +6 -6
- package/dist/http.js +1 -1
- package/dist/{index-BYv0hb8M.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-BGC-ENnj.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-BquQkhJi.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-COsQ-Mlz.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-DwOXkn1Y.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-DyET_VPP.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-DyET_VPP.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
package/README.md
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
**Storage is the missing primitive for agent-built software, and all you need is a library.**
|
|
4
4
|
|
|
5
|
-
> _Currently a private Gusto preview, published as `@gusto/baerly-storage`
|
|
5
|
+
> _Currently a private Gusto preview, published as `@gusto/baerly-storage` privately under the `@gusto` org on npm (npmjs.com)._
|
|
6
6
|
|
|
7
|
-
`baerly-storage` is a library that turns an S3-compatible bucket into a document database.
|
|
7
|
+
`baerly-storage` is a library that turns an S3-compatible bucket into a document database. **There is no runtime. None.** All coordination — fencing, commit, compaction, garbage collection — runs inside the HTTP request that triggered it: no daemon, no leader, no service bill, no on-call. The only persistent component is your bucket.
|
|
8
8
|
|
|
9
|
-
~
|
|
9
|
+
Server bundle: ~110 KB gzipped on Cloudflare Workers, ~160 KB gzipped on Node. Browser client: ~5 KB gzipped. The whole public API fits in a single ~1000-line `dist/API.md` — small enough that an LLM can hold it in context.
|
|
10
10
|
|
|
11
|
-
[S3
|
|
11
|
+
[S3 does the hard parts](https://aws.amazon.com/blogs/aws/amazon-s3-update-strong-read-after-write-consistency/), `baerly-storage` is the coordination that fixes the API. Built like git: content-addressed documents, immutable log entries, and a single CAS-advanced pointer to HEAD. Document model, live queries, snapshot isolation — the whole surface in a `.d.ts` an LLM can use zero-shot.
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Apps sized for this primitive — small, server-only writes, ~10 GB ceiling, mechanical exit to Postgres when they cross it — get a tool that matches their shape instead of a stack that doesn't.
|
|
14
14
|
|
|
15
15
|
```
|
|
16
16
|
Compute → FaaS
|
|
@@ -18,6 +18,8 @@ Tokens → LLM API
|
|
|
18
18
|
Storage → this.
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
+
Almost every team already has an S3-compatible bucket — for exports, backups, CSV graveyards. The security review happened years ago; the budget exists.
|
|
22
|
+
|
|
21
23
|
## The whole backend
|
|
22
24
|
|
|
23
25
|
```diff
|
|
@@ -66,6 +68,7 @@ const { rows } = useLiveQuery<Ticket>({
|
|
|
66
68
|
- **No hostage situation.** Log entries are shaped like Postgres
|
|
67
69
|
logical-replication messages. `baerly export --target=postgres`
|
|
68
70
|
graduates you out, mechanically, on the day an app outgrows this.
|
|
71
|
+
- **Honest about its envelope.** Sized for ~10 GB / tenant, ~30 writes/min/collection sustained, ~100 collections / tenant. Crossing any of those is the success signal to graduate.
|
|
69
72
|
|
|
70
73
|
## Quick start
|
|
71
74
|
|
|
@@ -83,6 +86,7 @@ For a runnable multi-tab demo see [`examples/react-node/`](./examples/react-node
|
|
|
83
86
|
## Go deeper
|
|
84
87
|
|
|
85
88
|
- 📖 **The essay** — [*Storage Is the Missing Primitive for Agent-Built Software*](https://docs.google.com/document/d/1jpMR-dV9wCprtzY2DUxAg_NZTrAf81OcB_vxKhiCPQ0/edit?tab=t.vo58xtzxjwr) [TODO: Replace with external link on publish]
|
|
89
|
+
- 🧭 **How it works** — [`docs/about/how-it-works.md`](./docs/about/how-it-works.md) (the plain-language mental model — bucket + one atomic pointer flip)
|
|
86
90
|
- 🧱 **Product thesis** — [`docs/about/thesis.md`](./docs/about/thesis.md)
|
|
87
91
|
- 🏗️ **Architecture** — [`docs/contributing/architecture.md`](./docs/contributing/architecture.md)
|
|
88
92
|
- 🔧 **Embed by hand** — [`docs/guide/embed.md`](./docs/guide/embed.md) (drop baerly into any existing Node app in ~30 lines)
|
package/dist/API.md
CHANGED
|
@@ -26,13 +26,19 @@ import {
|
|
|
26
26
|
MemoryStorage, // in-memory `Storage`; canonical for tests
|
|
27
27
|
type Collection, type Query,
|
|
28
28
|
type DocumentData,
|
|
29
|
+
type RowOf, type CollectionNames, // row-shape inference from a bound config
|
|
29
30
|
BaerlyError, type BaerlyErrorCode,
|
|
30
31
|
defineConfig, // narrower; root barrel
|
|
31
32
|
} from "@gusto/baerly-storage";
|
|
32
33
|
|
|
33
34
|
// Scaffold-aware config (`app`, `tenant`, `target`, `domain`, …)
|
|
34
|
-
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
35
|
-
// → use this one inside `baerly.config.ts`.
|
|
35
|
+
import { defineConfig, type RowOf } from "@gusto/baerly-storage/config";
|
|
36
|
+
// → use this one inside `baerly.config.ts`. `RowOf` is exported here too
|
|
37
|
+
// so `baerly.config.ts` siblings (e.g. `types.ts`) can import the inferred
|
|
38
|
+
// row type without reaching into the server barrel.
|
|
39
|
+
|
|
40
|
+
// HTTP helpers — for embed-by-hand routers that don't mount `createRouter`
|
|
41
|
+
import { createRouter, mapError } from "@gusto/baerly-storage/http";
|
|
36
42
|
|
|
37
43
|
// Browser / Node client (HTTP)
|
|
38
44
|
import {
|
|
@@ -77,6 +83,14 @@ await db.collection("tickets").insert({ title: "first ticket", status: "open" })
|
|
|
77
83
|
const open = await db.collection("tickets").where({ status: "open" }).all();
|
|
78
84
|
```
|
|
79
85
|
|
|
86
|
+
**`MemoryStorage` is per-instance.** Each `new MemoryStorage()`
|
|
87
|
+
backs an independent in-process bucket — two `Db` instances built
|
|
88
|
+
against two `new MemoryStorage()`s see two empty, isolated stores.
|
|
89
|
+
This is what makes it the canonical test fixture: one fresh instance
|
|
90
|
+
per test gives a hermetic bucket without `beforeEach` cleanup. Pass
|
|
91
|
+
the *same* `MemoryStorage` instance to multiple `Db` constructors
|
|
92
|
+
when you want two writers contending on one bucket.
|
|
93
|
+
|
|
80
94
|
Full `Db.create` config:
|
|
81
95
|
|
|
82
96
|
```ts
|
|
@@ -88,6 +102,23 @@ Db.create<TConfig>({
|
|
|
88
102
|
});
|
|
89
103
|
```
|
|
90
104
|
|
|
105
|
+
**`Db<typeof config>` is a usable type.** `Db.create({ ..., config })`
|
|
106
|
+
returns `Db<typeof config>`, and that type is exported from the root
|
|
107
|
+
barrel — so a test or DI helper can pin it without inferring through
|
|
108
|
+
the factory call site:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import type { Db } from "@gusto/baerly-storage";
|
|
112
|
+
import type config from "./baerly.config";
|
|
113
|
+
|
|
114
|
+
let cached: Db<typeof config> | undefined;
|
|
115
|
+
export function setDbForTesting(db: Db<typeof config>) { cached = db; }
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The narrowed `Db<typeof config>` carries the same `collection(name)`
|
|
119
|
+
overloads as the inferred return; `Db` (no parameter) widens to
|
|
120
|
+
`Db<UnboundConfig>` and accepts any string collection name.
|
|
121
|
+
|
|
91
122
|
## `db.collection(name)` → `Collection<T>`
|
|
92
123
|
|
|
93
124
|
`Collection<T>` carries the common-case verbs directly (collection-level
|
|
@@ -232,6 +263,19 @@ Two ways to get a typed row:
|
|
|
232
263
|
`createBaerlyClient`. `db.collection("tickets")` returns
|
|
233
264
|
`Collection<RowOf<TConfig, "tickets">>`. No generic, no cast.
|
|
234
265
|
|
|
266
|
+
`RowOf<TConfig, "tickets">` is also a usable type when you need
|
|
267
|
+
to name the row shape outside the chain — route-handler return
|
|
268
|
+
types, response-schema bridges, helpers that take a row by hand:
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
import type { RowOf } from "@gusto/baerly-storage";
|
|
272
|
+
import type config from "./baerly.config";
|
|
273
|
+
|
|
274
|
+
type Ticket = RowOf<typeof config, "tickets">;
|
|
275
|
+
// ^ same shape as `db.collection("tickets").all()` row.
|
|
276
|
+
// `CollectionNames<typeof config>` is the union of valid names.
|
|
277
|
+
```
|
|
278
|
+
|
|
235
279
|
2. **Falls back to `DocumentData`** when no config is bound. Cast at
|
|
236
280
|
the construction site for a narrower row shape:
|
|
237
281
|
```ts
|
|
@@ -273,6 +317,39 @@ try {
|
|
|
273
317
|
| `PayloadTooLarge` | 413 | Body > 1 MiB cap |
|
|
274
318
|
| `UnsatisfiablePredicate` | 400 | Predicate is well-formed but contradicts itself (empty `in` set, etc.) |
|
|
275
319
|
|
|
320
|
+
### Mapping errors to HTTP yourself
|
|
321
|
+
|
|
322
|
+
`baerlyWorker` and `baerlyNode` already translate `BaerlyError` →
|
|
323
|
+
HTTP status + wire envelope; the table above is what they implement.
|
|
324
|
+
If you mount the kernel's router directly (`createRouter` from
|
|
325
|
+
`@gusto/baerly-storage/http`), you get the same translation for free
|
|
326
|
+
under `/v1/*`.
|
|
327
|
+
|
|
328
|
+
For an **embed-by-hand** router (your own Hono / Express / Fastify
|
|
329
|
+
app calling `Db` directly, layering custom routes on top), reach
|
|
330
|
+
for `mapError` from the same subpath — it consumes the table above
|
|
331
|
+
in one call and returns the envelope and status code, so handlers
|
|
332
|
+
don't grow a five-arm `if (err.code === ...)` ladder:
|
|
333
|
+
|
|
334
|
+
```ts
|
|
335
|
+
import { mapError } from "@gusto/baerly-storage/http";
|
|
336
|
+
|
|
337
|
+
app.post("/notes", async (c) => {
|
|
338
|
+
try {
|
|
339
|
+
const { _id } = await db.collection("notes").insert(await c.req.json());
|
|
340
|
+
return c.json({ _id }, 201);
|
|
341
|
+
} catch (err) {
|
|
342
|
+
const { status, envelope } = mapError(err);
|
|
343
|
+
return c.json(envelope, status);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
`mapError` accepts any thrown value — non-`BaerlyError` throws fall
|
|
349
|
+
through to `500 Internal` with the message redacted, and the
|
|
350
|
+
underlying error is logged via the observability channel. The HTTP
|
|
351
|
+
status / envelope shape is locked.
|
|
352
|
+
|
|
276
353
|
## `defineConfig({ app, tenant, target, collections })`
|
|
277
354
|
|
|
278
355
|
Scaffold-aware: lives at `@gusto/baerly-storage/config`. Holds both deploy
|
|
@@ -284,7 +361,7 @@ import { defineConfig } from "@gusto/baerly-storage/config";
|
|
|
284
361
|
import { z } from "zod";
|
|
285
362
|
|
|
286
363
|
const TicketSchema = z.object({
|
|
287
|
-
_id: z.string()
|
|
364
|
+
_id: z.string(), // required — see callout below
|
|
288
365
|
status: z.enum(["open", "closed"]),
|
|
289
366
|
title: z.string().min(1),
|
|
290
367
|
tags: z.array(z.string()).optional(),
|
|
@@ -309,6 +386,18 @@ post-image: `update` and `replace` see the full doc, not just the
|
|
|
309
386
|
patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`,
|
|
310
387
|
mapped to HTTP 422.
|
|
311
388
|
|
|
389
|
+
**Author `_id` as required, not `.optional()`.** The validator runs
|
|
390
|
+
on the post-image — by the time it fires, the server has already
|
|
391
|
+
filled in a UUIDv7 `_id` for inserts that omit it, so every row the
|
|
392
|
+
validator sees has `_id` present. Declaring `_id: z.string()`
|
|
393
|
+
(required) matches that runtime invariant. `Collection<T>.insert`
|
|
394
|
+
still accepts a doc without `_id` (the public signature is
|
|
395
|
+
`insert(doc: Partial<T> & DocumentData)`), so authoring `_id` as
|
|
396
|
+
required does not break the "omit and let the server mint it" path.
|
|
397
|
+
The win is on the read side: `db.collection("tickets").all()` is
|
|
398
|
+
typed `Ticket[]` with `_id: string` (required), so route handlers
|
|
399
|
+
and response schemas don't need a parallel "_id-required" row type.
|
|
400
|
+
|
|
312
401
|
Indexes: declared here, threaded into `Db.create` automatically. The
|
|
313
402
|
read-path auto-planner picks an index when the predicate matches;
|
|
314
403
|
mismatches fall back to the full scan with a metric bump (correctness
|
|
@@ -360,15 +449,13 @@ interface SinceResponse {
|
|
|
360
449
|
interface LogEntry {
|
|
361
450
|
readonly lsn: string; // opaque cursor; lex-asc, monotonic
|
|
362
451
|
readonly commit_ts: string; // ISO-8601 ms
|
|
363
|
-
readonly op: "I" | "U" | "D"
|
|
452
|
+
readonly op: "I" | "U" | "D";
|
|
364
453
|
readonly collection: string;
|
|
365
|
-
readonly doc_id
|
|
366
|
-
readonly
|
|
367
|
-
readonly patch?: DocumentData; // U — JSON-merge-patch (RFC 7386)
|
|
368
|
-
readonly schema_version: number;
|
|
454
|
+
readonly doc_id: string; // I/U/D only
|
|
455
|
+
readonly after?: DocumentData; // I/U — post-image (Debezium's `after`)
|
|
369
456
|
readonly session: string;
|
|
370
457
|
readonly seq: number;
|
|
371
|
-
// `
|
|
458
|
+
// `before` / `key_old` / `origin` are optional; see `LogEntry` JSDoc.
|
|
372
459
|
}
|
|
373
460
|
```
|
|
374
461
|
|
|
@@ -470,6 +557,16 @@ Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
|
|
|
470
557
|
`400 SchemaError "Request body must be { doc: object }"` — wording is
|
|
471
558
|
locked by `assertJsonBodyField` in the kernel.
|
|
472
559
|
|
|
560
|
+
### Liveness probe (`GET /v1/healthz`)
|
|
561
|
+
|
|
562
|
+
`baerlyWorker` and `baerlyNode` both mount an anonymous
|
|
563
|
+
`GET /v1/healthz` → `200 {"ok":true}`. It is checked **before** the
|
|
564
|
+
verifier and observability, so it never 401s and never floods your
|
|
565
|
+
logs — wire your platform's liveness/readiness probe straight to it.
|
|
566
|
+
If your probe path is fixed to something else (a k8s readiness path,
|
|
567
|
+
say), put a custom route in front of the kernel (see "Recipe — custom
|
|
568
|
+
routes in front of `baerlyNode`" below).
|
|
569
|
+
|
|
473
570
|
### Read modifiers (query params)
|
|
474
571
|
|
|
475
572
|
`GET /v1/c/:collection` accepts three JSON-encoded query params; all are
|
|
@@ -504,7 +601,6 @@ baerlyNode({
|
|
|
504
601
|
storage: s3Storage({ bucket: "…", credentials: { … } }),
|
|
505
602
|
verifier: bearerJwt({ jwks, issuer, audience }),
|
|
506
603
|
webRoot: "dist/client", // optional SPA static-serve
|
|
507
|
-
maintenance: { collections: ["tickets"], tenants: ["acme"] }, // optional
|
|
508
604
|
}).listen(PORT);
|
|
509
605
|
```
|
|
510
606
|
|
|
@@ -521,6 +617,16 @@ custom `Verifier` on the factory) when you're ready to gate by wire
|
|
|
521
617
|
credentials. Production CF Worker recipes layer CF Access in front of
|
|
522
618
|
the Worker route; the verifier reads the resulting JWT:
|
|
523
619
|
|
|
620
|
+
**`auth` only gates the kernel's HTTP router.** `auth: "none"` /
|
|
621
|
+
`"shared-secret"` is read by `baerlyWorker` / `baerlyNode` / the
|
|
622
|
+
underlying `createRouter` — it controls who can hit `/v1/*`. If you
|
|
623
|
+
use `Db` directly (no `createRouter`, no `baerlyWorker`/`baerlyNode`,
|
|
624
|
+
e.g. server-internal jobs or your own Hono router), `auth` is
|
|
625
|
+
inert: every `Db.create` callsite already carries an explicit
|
|
626
|
+
`tenant:`, and your handler's own auth layer decides who reaches
|
|
627
|
+
the call. Set `auth: "none"` in the config to silence the typecheck
|
|
628
|
+
requirement in that case.
|
|
629
|
+
|
|
524
630
|
```ts
|
|
525
631
|
// baerly.config.ts
|
|
526
632
|
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
@@ -724,6 +830,51 @@ observability gap is being tracked as a follow-up. If you also need
|
|
|
724
830
|
PATCH/PUT/DELETE on the same collection, repeat steps (1) and (2) for
|
|
725
831
|
each verb.
|
|
726
832
|
|
|
833
|
+
## Recipe — custom routes in front of `baerlyNode`
|
|
834
|
+
|
|
835
|
+
`baerlyNode(...).listen(port)` is the shortcut for the common case:
|
|
836
|
+
no custom routes, the kernel owns the whole port. To put your own
|
|
837
|
+
route in front of the kernel (a fixed-path health probe, a
|
|
838
|
+
trusted-stamp write route à la the recipe above), grab the
|
|
839
|
+
web-standard `fetch` handler off the handle instead of calling
|
|
840
|
+
`.listen()`, and serve it yourself. `serve()` here is the same
|
|
841
|
+
`@hono/node-server` entry `.listen()` uses internally — you're just
|
|
842
|
+
taking ownership of the dispatch:
|
|
843
|
+
|
|
844
|
+
```ts
|
|
845
|
+
// src/server/index.ts
|
|
846
|
+
import { serve } from "@hono/node-server";
|
|
847
|
+
import { baerlyNode, s3Storage } from "@gusto/baerly-storage/node";
|
|
848
|
+
import config from "../../baerly.config.ts";
|
|
849
|
+
|
|
850
|
+
const inner = baerlyNode({
|
|
851
|
+
config,
|
|
852
|
+
storage: s3Storage(/* … */),
|
|
853
|
+
webRoot: "dist/client", // still serves the SPA + /v1/* as usual
|
|
854
|
+
});
|
|
855
|
+
|
|
856
|
+
serve({
|
|
857
|
+
port: Number(process.env["PORT"] ?? 8080),
|
|
858
|
+
fetch: (req) =>
|
|
859
|
+
new URL(req.url).pathname === "/health-check"
|
|
860
|
+
? Response.json({ ok: true })
|
|
861
|
+
: inner.fetch(req),
|
|
862
|
+
});
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
The handle's `fetch` is the documented embedding seam (it's also what
|
|
866
|
+
the Vite dev middleware and tests consume) — there's no separate
|
|
867
|
+
`createApp` to reach for. If you don't need a *custom* probe path,
|
|
868
|
+
skip all of this and point your platform at the built-in
|
|
869
|
+
`GET /v1/healthz` (see above).
|
|
870
|
+
|
|
871
|
+
> **Monorepo note.** `@hono/node-server` (and its `hono` peer) ship
|
|
872
|
+
> as dependencies of the Node adapter, so the `serve` import resolves
|
|
873
|
+
> out of the box in a scaffolded app. In a monorepo that prunes
|
|
874
|
+
> unused peers (e.g. `yarn workspaces focus` in CI), add
|
|
875
|
+
> `@hono/node-server` to the app's own `dependencies` so the import
|
|
876
|
+
> survives the prune.
|
|
877
|
+
|
|
727
878
|
## Recipe — wrapping the client `fetch`
|
|
728
879
|
|
|
729
880
|
`createBaerlyClient({ fetch: customFetcher })` is the one composable
|
|
@@ -25,9 +25,9 @@ declare const AUTH_CONFIG_VALUES: readonly ["none", "shared-secret"];
|
|
|
25
25
|
* {@link DocumentValue}.
|
|
26
26
|
*
|
|
27
27
|
* The document **body** itself must be an object (not an array) —
|
|
28
|
-
* Baerly's writer is built on JSON Merge Patch (RFC
|
|
28
|
+
* Baerly's writer is built on JSON Merge Patch (RFC 7386), which
|
|
29
29
|
* is only defined over object documents. Array *values* at any
|
|
30
|
-
* nested level are fine; per RFC
|
|
30
|
+
* nested level are fine; per RFC 7386, an array in a patch
|
|
31
31
|
* replaces the target array wholesale (Baerly has no array-merge
|
|
32
32
|
* semantics).
|
|
33
33
|
*/
|
|
@@ -95,15 +95,15 @@ interface PredicateWire {
|
|
|
95
95
|
* `collections.<name>.indexes[]` and is threaded through
|
|
96
96
|
* `Writer` via `WriterOptions.indexes`.
|
|
97
97
|
*
|
|
98
|
-
* Validated synchronously by `validateIndexDefinition`
|
|
99
|
-
*
|
|
100
|
-
* throws `BaerlyError{code: "SchemaError"}` before the first commit.
|
|
98
|
+
* Validated synchronously by `validateIndexDefinition` (in
|
|
99
|
+
* `@baerly/server`) at writer construction — see `name` below.
|
|
101
100
|
*/
|
|
102
101
|
interface IndexDefinition {
|
|
103
102
|
/**
|
|
104
|
-
* Stable path-safe identifier
|
|
105
|
-
*
|
|
106
|
-
*
|
|
103
|
+
* Stable path-safe identifier, used directly as a key segment under
|
|
104
|
+
* `<logPrefix>/index/<name>/...`. Must match `/^[a-z][a-z0-9_]*$/`.
|
|
105
|
+
* A reserved leading-`_` name throws `InvalidConfig`; a malformed
|
|
106
|
+
* name throws `SchemaError`. See docs/adr/007-layout-versioning-cordon.md.
|
|
107
107
|
*/
|
|
108
108
|
readonly name: string;
|
|
109
109
|
/**
|
|
@@ -304,6 +304,15 @@ interface BaerlyConfig {
|
|
|
304
304
|
* are set — this is the "dev default in config, prod override via
|
|
305
305
|
* env" recipe.
|
|
306
306
|
*
|
|
307
|
+
* **`auth` only gates the kernel's HTTP router.** It's consumed by
|
|
308
|
+
* `baerlyWorker` / `baerlyNode` / `createRouter` to decide who can
|
|
309
|
+
* hit `/v1/*`. If you use `Db` directly without mounting any of
|
|
310
|
+
* those (server-internal jobs, your own Hono/Express router, a CLI
|
|
311
|
+
* embedding the kernel), this field is inert — each `Db.create` call
|
|
312
|
+
* already carries an explicit `tenant:`, and your handler's own
|
|
313
|
+
* auth layer decides who reaches the call. Set `auth: "none"` to
|
|
314
|
+
* silence the typecheck requirement in that case.
|
|
315
|
+
*
|
|
307
316
|
* Field is required on `BaerlyAppConfig`. Omitting it causes both a
|
|
308
317
|
* TypeScript error at `defineConfig({...})` and (defensively) an
|
|
309
318
|
* `InvalidConfig` error at adapter module init.
|
|
@@ -477,4 +486,4 @@ type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {
|
|
|
477
486
|
} ? S extends SchemaValidator<unknown, infer Out> ? Out : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;
|
|
478
487
|
//#endregion
|
|
479
488
|
export { CollectionNames as a, defineConfig as c, IndexDefinition as d, DocumentData as f, CollectionDefinition as i, SchemaIssue as l, JSONValue as m, BaerlyAppConfig as n, RowOf as o, DocumentValue as p, BaerlyConfig as r, UnboundConfig as s, AuthConfig as t, SchemaValidator as u };
|
|
480
|
-
//# sourceMappingURL=app-config-
|
|
489
|
+
//# sourceMappingURL=app-config-C0Bbw_Z6.d.ts.map
|
package/dist/app-config.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CollectionNames, c as defineConfig, f as DocumentData, i as CollectionDefinition, n as BaerlyAppConfig, o as RowOf, p as DocumentValue, r as BaerlyConfig, s as UnboundConfig, t as AuthConfig } from "./app-config-
|
|
1
|
+
import { a as CollectionNames, c as defineConfig, f as DocumentData, i as CollectionDefinition, n as BaerlyAppConfig, o as RowOf, p as DocumentValue, r as BaerlyConfig, s as UnboundConfig, t as AuthConfig } from "./app-config-C0Bbw_Z6.js";
|
|
2
2
|
export { AuthConfig, BaerlyAppConfig, BaerlyConfig, CollectionDefinition, CollectionNames, type DocumentData, type DocumentValue, RowOf, UnboundConfig, defineConfig };
|
package/dist/app-config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-config.js","names":[],"sources":["../packages/protocol/src/app-config.ts"],"sourcesContent":["/**\n * Collection-config schema types + `defineConfig` identity helper.\n *\n * Lives in `@baerly/protocol` (the cross-platform package) so the\n * scaffold's `baerly.config.ts` and the client can reference these\n * types without transitively dragging Node-only server modules\n * (`AsyncLocalStorage` etc.) into their import graph.\n *\n * Runtime helpers that operate on these shapes —\n * `collectionsToMaps`, `validateIndexDefinition`, `validateOrThrow`\n * — stay in `@baerly/server`; they have impl detail that's allowed\n * to depend on Node-only modules.\n *\n * @see ./indexes.ts — `IndexDefinition` type.\n * @see ./schema.ts — `SchemaValidator` / `SchemaIssue` types.\n *\n * @example\n * ```ts\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * export default defineConfig({\n * app: \"tickets\",\n * tenant: \"acme\",\n * target: \"cloudflare\",\n * collections: {\n * tickets: {\n * indexes: [\n * { name: \"by_status\", on: \"status\" },\n * { name: \"by_assignee\", on: \"assignee\" },\n * ],\n * },\n * },\n * });\n * ```\n */\n\nimport type { AUTH_CONFIG_VALUES } from \"./constants.ts\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport type { SchemaValidator } from \"./schema.ts\";\n\n// Cross-platform protocol types re-exported from `@gusto/baerly-storage/config`\n// so the scaffold's `baerly.config.ts` and its sibling `types.ts` can\n// pull every shape they need from one DOM-pure entry. `DocumentData`\n// is the row-shape constraint that scaffolded `interface Note extends\n// DocumentData {...}` declarations target; re-exporting here keeps the\n// example's typecheck graph from reaching into the server barrel.\nexport type { DocumentData, DocumentValue } from \"./json.ts\";\n\n/**\n * One collection's declarative config. Today `indexes` and `schema`\n * are consumed; future tickets add `replica_identity` and lifecycle\n * hooks.\n */\nexport interface CollectionDefinition {\n /**\n * Secondary indexes declared for this collection. Each declared\n * index produces one zero-byte PUT per commit (when the indexed\n * field is set on the doc) inside the same fence as the log\n * entry and content body. See `./indexes.ts` for the key shape.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n /**\n * Optional schema for this collection. When set, every server-side\n * `insert` / `update` / `replace` validates the resulting post-image\n * before committing — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries.\n *\n * Adapter: StandardSchemaV1 (see `./schema.ts`). Compatible with\n * Zod 3.24+, Valibot 0.36+, ArkType 2.0+ today; any future library\n * implementing the spec works without a code change here.\n *\n * `undefined` means no validation — every write proceeds as today\n * (zero overhead, today's tests untouched).\n *\n * @remarks\n * **`.nullable()` is not supported.** baerly's `DocumentValue` excludes\n * `null` by design (see `packages/protocol/src/json.ts`). `null` is\n * reserved as the JSON-merge-patch (RFC 7386) field-deletion sentinel\n * in `update` patches. Use `.optional()` for absent values.\n *\n * Validation runs on the post-image: `update` and `replace` see the\n * full doc, not just the patch. Failures throw\n * `BaerlyError{ code: \"SchemaError\", issues: [...] }`.\n */\n readonly schema?: SchemaValidator;\n}\n\n/**\n * The full `baerly.config.ts` runtime shape. Re-exported from\n * `baerly-storage` and consumed by the day-1 `npm create baerly`\n * scaffold + the `baerly admin rebuild-index` CLI.\n */\nexport interface BaerlyConfig {\n /**\n * Per-collection declarations, keyed by collection name. Required\n * (declare `{}` when you have no collections yet) — this keeps the\n * config interface from being structurally empty, which would\n * trigger TypeScript's weak-type check when the adapter accepts\n * the literal as `BaerlyWorkerOptions.config` / `BaerlyNodeOptions.config`.\n */\n readonly collections: Readonly<Record<string, CollectionDefinition>>;\n}\n\n/**\n * Auth posture for the deployed app. REQUIRED on `BaerlyAppConfig`.\n *\n * - `\"none\"`: no header check; every request resolves to\n * `config.tenant`. Use for local dev, intranet deployments, CLI\n * tools — contexts where the network seam itself is the trust\n * boundary. The adapter logs one startup line so the state is not\n * silent.\n * - `\"shared-secret\"`: bearer-token check; the adapter reads\n * `SHARED_SECRET` from the runtime env and pins every request to\n * `config.tenant`. Module init throws `BaerlyError(\"InvalidConfig\", ...)`\n * on first `fetch` if the env var is missing/empty.\n *\n * For custom verifiers (Cloudflare Access, JWT, SigV4, …), pass a\n * `Verifier` directly to the adapter factory's `verifier:` option.\n * The factory `verifier:` silently overrides `config.auth` when both\n * are set — this is the \"dev default in config, prod override via\n * env\" recipe.\n *\n * Field is required on `BaerlyAppConfig`. Omitting it causes both a\n * TypeScript error at `defineConfig({...})` and (defensively) an\n * `InvalidConfig` error at adapter module init.\n *\n * The literal values come from\n * {@link AUTH_CONFIG_VALUES} so the runtime-only consumers (doctor,\n * adapter) share the same source of truth.\n */\nexport type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];\n\n/**\n * `BaerlyAppConfig` extends `BaerlyConfig` with scaffold-flavoured\n * deploy metadata (`target`, `domain`, `cloudflareAccess`, etc.).\n *\n * Exposed at `@gusto/baerly-storage/config`. Imported by the\n * `baerly.config.ts` that `npm create baerly` emits, and by anyone\n * who wants IDE/`tsgo` type inference on the full scaffold-aware\n * config shape on top of the runtime `BaerlyConfig.collections` map.\n *\n * One `baerly.config.ts` carries both scaffold metadata (consumed by\n * `baerly deploy` / `baerly doctor`) and the runtime schema\n * (consumed by `Db.create`). The literal-pinned return type of\n * {@link defineConfig} makes `collections` flow through to\n * `Db.create<TConfig>` and `createBaerlyClient<TConfig>`.\n */\nexport interface BaerlyAppConfig extends BaerlyConfig {\n /** Bucket-prefix for this baerly app. One bucket per app. */\n readonly app: string;\n /**\n * Default tenant pin for `Verifier`s that don't derive a tenant\n * from a claim. Production `Verifier`s (`bearerJwt`,\n * `cloudflareAccess`) ignore this and derive `tenantPrefix` from\n * the request.\n */\n readonly tenant: string;\n /**\n * Deploy target — `\"cloudflare\"` or `\"node\"`.\n * Read by `baerly deploy` to dispatch the correct deploy command.\n */\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Optional. Custom domain for the deployed service. Cloudflare:\n * wired to the Worker as a route. Node: rendered into the\n * Dockerfile's `EXPOSE` and the emitted readme.\n */\n readonly domain?: string | undefined;\n /**\n * Names of secrets the deployed runtime needs. `baerly deploy`\n * and `baerly doctor` check each against the platform's secret\n * store and warn (deploy) / report (doctor) when missing.\n * Default treatment (when unset) is `[\"SHARED_SECRET\"]` — matches\n * the scaffolder's emitted Verifier wiring.\n */\n readonly requiredSecrets?: readonly string[];\n /**\n * Optional Cloudflare Access app config. When set, the production\n * CF template prefers `cloudflareAccess()` as the `Verifier` and\n * `baerly doctor --target=cloudflare` walks the CF Access app\n * config to confirm the audience tag matches.\n *\n * - `teamDomain` — CF Access team domain, e.g. `\"acme\"`.\n * - `audienceTag` — Application Audience (AUD) tag from the CF\n * Access app, 64 lowercase-hex characters.\n */\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /**\n * Optional observability overrides. The templates already\n * read `LOG_LEVEL` from the runtime env; this field is a\n * typed-config alternative for deployments that prefer to pin\n * defaults in source. See `docs/guide/observability.md` for the\n * canonical-line shape and `docs/contributing/conventions/observability.md` for\n * the one-canonical-line-per-unit-of-work rule.\n *\n * - `level` — lowest record level reaching the sink. Falls back\n * to the `LOG_LEVEL` env var, then to `\"info\"`.\n */\n readonly observability?: {\n readonly level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n };\n /**\n * Auth posture. See {@link AuthConfig} for the full per-value\n * semantics, the failure modes, and the \"dev default, prod override\"\n * recipe. Field is required — omission fails typecheck and (for\n * adapters that didn't supply a `verifier:` override) throws\n * `BaerlyError(\"InvalidConfig\", ...)` at first request.\n */\n readonly auth: AuthConfig;\n}\n\n/**\n * Identity helper that pins the config's TypeScript shape so IDEs\n * surface autocomplete and `tsgo --noEmit` catches typos at write\n * time. Returns its input verbatim — no runtime transformation.\n *\n * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`\n * (the shape `npm create baerly` emits, which carries `app`,\n * `tenant`, `target` deploy metadata) and one for the runtime\n * `BaerlyConfig` shape (just `collections`, used by tests and by\n * apps that wire deploy metadata in some other way). Both preserve\n * the literal shape of `cfg` via `<const C>` so `CollectionNames<C>`\n * and `RowOf<C, N>` resolve to literal unions.\n */\nexport function defineConfig<const C extends BaerlyAppConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C {\n return cfg;\n}\n\n/**\n * Sentinel `BaerlyConfig` used as the default `TConfig` parameter\n * by consumers (`Db<TConfig>`, `BaerlyClient<TConfig>`). Setting\n * `collections` to `Record<string, CollectionDefinition>` makes\n * `CollectionNames<UnboundConfig>` widen to `string`, so the single\n * typed accessor `db.collection<N extends CollectionNames<TConfig>>(name: N)`\n * still resolves for kernel-internal paths (which carry no bound\n * config) — those callers see `name: string` and the row type\n * defaults to `DocumentData` via {@link RowOf}'s `Record<string, unknown>`\n * fallback. Consumers who bind a config via {@link defineConfig}\n * narrow `CollectionNames<TConfig>` to a literal union and lose the\n * string-typo accepting behaviour, which is the design intent.\n */\nexport type UnboundConfig = { readonly collections: Record<string, CollectionDefinition> };\n\n/**\n * Set of declared collection names on a `BaerlyConfig`, as a string\n * union. Resolves to `never` when no `collections` are declared\n * (notably for `UnboundConfig`), which the typed `Db` / client\n * overloads use to disable narrowing for unbound consumers.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Names = CollectionNames<typeof config>; // \"tickets\" | \"audits\"\n * ```\n */\nexport type CollectionNames<C extends BaerlyConfig> = C extends {\n readonly collections: infer Cs;\n}\n ? Extract<keyof Cs, string>\n : never;\n\n/**\n * Row type for collection `N` on config `C`. Resolves to the\n * `StandardSchemaV1` output type of `C[\"collections\"][N][\"schema\"]`\n * when one is declared; otherwise falls back to\n * `Record<string, unknown>`.\n *\n * The fallback is intentionally wider than the protocol's\n * `DocumentData`. Downstream call sites that need\n * `DocumentData` (e.g. `Collection<T extends DocumentData>`)\n * apply the intersection at their own seam — keeping that\n * constraint local to the consumer keeps THIS file independent of\n * `@baerly/protocol/src/json.ts`.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Ticket = RowOf<typeof config, \"tickets\">; // z.infer<typeof TicketSchema>\n * type Audit = RowOf<typeof config, \"audits\">; // Record<string, unknown>\n * ```\n */\nexport type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {\n readonly collections: infer Cs;\n}\n ? N extends keyof Cs\n ? Cs[N] extends { readonly schema: infer S }\n ? S extends SchemaValidator<unknown, infer Out>\n ? Out\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>;\n"],"mappings":";AAsOA,SAAgB,aAA2C,KAAW;CACpE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"app-config.js","names":[],"sources":["../packages/protocol/src/app-config.ts"],"sourcesContent":["/**\n * Collection-config schema types + `defineConfig` identity helper.\n *\n * Lives in `@baerly/protocol` (the cross-platform package) so the\n * scaffold's `baerly.config.ts` and the client can reference these\n * types without transitively dragging Node-only server modules\n * (`AsyncLocalStorage` etc.) into their import graph.\n *\n * Runtime helpers that operate on these shapes —\n * `collectionsToMaps`, `validateIndexDefinition`, `validateOrThrow`\n * — stay in `@baerly/server`; they have impl detail that's allowed\n * to depend on Node-only modules.\n *\n * @see ./indexes.ts — `IndexDefinition` type.\n * @see ./schema.ts — `SchemaValidator` / `SchemaIssue` types.\n *\n * @example\n * ```ts\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * export default defineConfig({\n * app: \"tickets\",\n * tenant: \"acme\",\n * target: \"cloudflare\",\n * collections: {\n * tickets: {\n * indexes: [\n * { name: \"by_status\", on: \"status\" },\n * { name: \"by_assignee\", on: \"assignee\" },\n * ],\n * },\n * },\n * });\n * ```\n */\n\nimport type { AUTH_CONFIG_VALUES } from \"./constants.ts\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport type { SchemaValidator } from \"./schema.ts\";\n\n// Cross-platform protocol types re-exported from `@gusto/baerly-storage/config`\n// so the scaffold's `baerly.config.ts` and its sibling `types.ts` can\n// pull every shape they need from one DOM-pure entry. `DocumentData`\n// is the row-shape constraint that scaffolded `interface Note extends\n// DocumentData {...}` declarations target; re-exporting here keeps the\n// example's typecheck graph from reaching into the server barrel.\nexport type { DocumentData, DocumentValue } from \"./json.ts\";\n\n/**\n * One collection's declarative config. Today `indexes` and `schema`\n * are consumed; future tickets add `replica_identity` and lifecycle\n * hooks.\n */\nexport interface CollectionDefinition {\n /**\n * Secondary indexes declared for this collection. Each declared\n * index produces one zero-byte PUT per commit (when the indexed\n * field is set on the doc) inside the same fence as the log\n * entry and content body. See `./indexes.ts` for the key shape.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n /**\n * Optional schema for this collection. When set, every server-side\n * `insert` / `update` / `replace` validates the resulting post-image\n * before committing — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries.\n *\n * Adapter: StandardSchemaV1 (see `./schema.ts`). Compatible with\n * Zod 3.24+, Valibot 0.36+, ArkType 2.0+ today; any future library\n * implementing the spec works without a code change here.\n *\n * `undefined` means no validation — every write proceeds as today\n * (zero overhead, today's tests untouched).\n *\n * @remarks\n * **`.nullable()` is not supported.** baerly's `DocumentValue` excludes\n * `null` by design (see `packages/protocol/src/json.ts`). `null` is\n * reserved as the JSON-merge-patch (RFC 7386) field-deletion sentinel\n * in `update` patches. Use `.optional()` for absent values.\n *\n * Validation runs on the post-image: `update` and `replace` see the\n * full doc, not just the patch. Failures throw\n * `BaerlyError{ code: \"SchemaError\", issues: [...] }`.\n */\n readonly schema?: SchemaValidator;\n}\n\n/**\n * The full `baerly.config.ts` runtime shape. Re-exported from\n * `baerly-storage` and consumed by the day-1 `npm create baerly`\n * scaffold + the `baerly admin rebuild-index` CLI.\n */\nexport interface BaerlyConfig {\n /**\n * Per-collection declarations, keyed by collection name. Required\n * (declare `{}` when you have no collections yet) — this keeps the\n * config interface from being structurally empty, which would\n * trigger TypeScript's weak-type check when the adapter accepts\n * the literal as `BaerlyWorkerOptions.config` / `BaerlyNodeOptions.config`.\n */\n readonly collections: Readonly<Record<string, CollectionDefinition>>;\n}\n\n/**\n * Auth posture for the deployed app. REQUIRED on `BaerlyAppConfig`.\n *\n * - `\"none\"`: no header check; every request resolves to\n * `config.tenant`. Use for local dev, intranet deployments, CLI\n * tools — contexts where the network seam itself is the trust\n * boundary. The adapter logs one startup line so the state is not\n * silent.\n * - `\"shared-secret\"`: bearer-token check; the adapter reads\n * `SHARED_SECRET` from the runtime env and pins every request to\n * `config.tenant`. Module init throws `BaerlyError(\"InvalidConfig\", ...)`\n * on first `fetch` if the env var is missing/empty.\n *\n * For custom verifiers (Cloudflare Access, JWT, SigV4, …), pass a\n * `Verifier` directly to the adapter factory's `verifier:` option.\n * The factory `verifier:` silently overrides `config.auth` when both\n * are set — this is the \"dev default in config, prod override via\n * env\" recipe.\n *\n * **`auth` only gates the kernel's HTTP router.** It's consumed by\n * `baerlyWorker` / `baerlyNode` / `createRouter` to decide who can\n * hit `/v1/*`. If you use `Db` directly without mounting any of\n * those (server-internal jobs, your own Hono/Express router, a CLI\n * embedding the kernel), this field is inert — each `Db.create` call\n * already carries an explicit `tenant:`, and your handler's own\n * auth layer decides who reaches the call. Set `auth: \"none\"` to\n * silence the typecheck requirement in that case.\n *\n * Field is required on `BaerlyAppConfig`. Omitting it causes both a\n * TypeScript error at `defineConfig({...})` and (defensively) an\n * `InvalidConfig` error at adapter module init.\n *\n * The literal values come from\n * {@link AUTH_CONFIG_VALUES} so the runtime-only consumers (doctor,\n * adapter) share the same source of truth.\n */\nexport type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];\n\n/**\n * `BaerlyAppConfig` extends `BaerlyConfig` with scaffold-flavoured\n * deploy metadata (`target`, `domain`, `cloudflareAccess`, etc.).\n *\n * Exposed at `@gusto/baerly-storage/config`. Imported by the\n * `baerly.config.ts` that `npm create baerly` emits, and by anyone\n * who wants IDE/`tsgo` type inference on the full scaffold-aware\n * config shape on top of the runtime `BaerlyConfig.collections` map.\n *\n * One `baerly.config.ts` carries both scaffold metadata (consumed by\n * `baerly deploy` / `baerly doctor`) and the runtime schema\n * (consumed by `Db.create`). The literal-pinned return type of\n * {@link defineConfig} makes `collections` flow through to\n * `Db.create<TConfig>` and `createBaerlyClient<TConfig>`.\n */\nexport interface BaerlyAppConfig extends BaerlyConfig {\n /** Bucket-prefix for this baerly app. One bucket per app. */\n readonly app: string;\n /**\n * Default tenant pin for `Verifier`s that don't derive a tenant\n * from a claim. Production `Verifier`s (`bearerJwt`,\n * `cloudflareAccess`) ignore this and derive `tenantPrefix` from\n * the request.\n */\n readonly tenant: string;\n /**\n * Deploy target — `\"cloudflare\"` or `\"node\"`.\n * Read by `baerly deploy` to dispatch the correct deploy command.\n */\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Optional. Custom domain for the deployed service. Cloudflare:\n * wired to the Worker as a route. Node: rendered into the\n * Dockerfile's `EXPOSE` and the emitted readme.\n */\n readonly domain?: string | undefined;\n /**\n * Names of secrets the deployed runtime needs. `baerly deploy`\n * and `baerly doctor` check each against the platform's secret\n * store and warn (deploy) / report (doctor) when missing.\n * Default treatment (when unset) is `[\"SHARED_SECRET\"]` — matches\n * the scaffolder's emitted Verifier wiring.\n */\n readonly requiredSecrets?: readonly string[];\n /**\n * Optional Cloudflare Access app config. When set, the production\n * CF template prefers `cloudflareAccess()` as the `Verifier` and\n * `baerly doctor --target=cloudflare` walks the CF Access app\n * config to confirm the audience tag matches.\n *\n * - `teamDomain` — CF Access team domain, e.g. `\"acme\"`.\n * - `audienceTag` — Application Audience (AUD) tag from the CF\n * Access app, 64 lowercase-hex characters.\n */\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /**\n * Optional observability overrides. The templates already\n * read `LOG_LEVEL` from the runtime env; this field is a\n * typed-config alternative for deployments that prefer to pin\n * defaults in source. See `docs/guide/observability.md` for the\n * canonical-line shape and `docs/contributing/conventions/observability.md` for\n * the one-canonical-line-per-unit-of-work rule.\n *\n * - `level` — lowest record level reaching the sink. Falls back\n * to the `LOG_LEVEL` env var, then to `\"info\"`.\n */\n readonly observability?: {\n readonly level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n };\n /**\n * Auth posture. See {@link AuthConfig} for the full per-value\n * semantics, the failure modes, and the \"dev default, prod override\"\n * recipe. Field is required — omission fails typecheck and (for\n * adapters that didn't supply a `verifier:` override) throws\n * `BaerlyError(\"InvalidConfig\", ...)` at first request.\n */\n readonly auth: AuthConfig;\n}\n\n/**\n * Identity helper that pins the config's TypeScript shape so IDEs\n * surface autocomplete and `tsgo --noEmit` catches typos at write\n * time. Returns its input verbatim — no runtime transformation.\n *\n * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`\n * (the shape `npm create baerly` emits, which carries `app`,\n * `tenant`, `target` deploy metadata) and one for the runtime\n * `BaerlyConfig` shape (just `collections`, used by tests and by\n * apps that wire deploy metadata in some other way). Both preserve\n * the literal shape of `cfg` via `<const C>` so `CollectionNames<C>`\n * and `RowOf<C, N>` resolve to literal unions.\n */\nexport function defineConfig<const C extends BaerlyAppConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C {\n return cfg;\n}\n\n/**\n * Sentinel `BaerlyConfig` used as the default `TConfig` parameter\n * by consumers (`Db<TConfig>`, `BaerlyClient<TConfig>`). Setting\n * `collections` to `Record<string, CollectionDefinition>` makes\n * `CollectionNames<UnboundConfig>` widen to `string`, so the single\n * typed accessor `db.collection<N extends CollectionNames<TConfig>>(name: N)`\n * still resolves for kernel-internal paths (which carry no bound\n * config) — those callers see `name: string` and the row type\n * defaults to `DocumentData` via {@link RowOf}'s `Record<string, unknown>`\n * fallback. Consumers who bind a config via {@link defineConfig}\n * narrow `CollectionNames<TConfig>` to a literal union and lose the\n * string-typo accepting behaviour, which is the design intent.\n */\nexport type UnboundConfig = { readonly collections: Record<string, CollectionDefinition> };\n\n/**\n * Set of declared collection names on a `BaerlyConfig`, as a string\n * union. Resolves to `never` when no `collections` are declared\n * (notably for `UnboundConfig`), which the typed `Db` / client\n * overloads use to disable narrowing for unbound consumers.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Names = CollectionNames<typeof config>; // \"tickets\" | \"audits\"\n * ```\n */\nexport type CollectionNames<C extends BaerlyConfig> = C extends {\n readonly collections: infer Cs;\n}\n ? Extract<keyof Cs, string>\n : never;\n\n/**\n * Row type for collection `N` on config `C`. Resolves to the\n * `StandardSchemaV1` output type of `C[\"collections\"][N][\"schema\"]`\n * when one is declared; otherwise falls back to\n * `Record<string, unknown>`.\n *\n * The fallback is intentionally wider than the protocol's\n * `DocumentData`. Downstream call sites that need\n * `DocumentData` (e.g. `Collection<T extends DocumentData>`)\n * apply the intersection at their own seam — keeping that\n * constraint local to the consumer keeps THIS file independent of\n * `@baerly/protocol/src/json.ts`.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Ticket = RowOf<typeof config, \"tickets\">; // z.infer<typeof TicketSchema>\n * type Audit = RowOf<typeof config, \"audits\">; // Record<string, unknown>\n * ```\n */\nexport type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {\n readonly collections: infer Cs;\n}\n ? N extends keyof Cs\n ? Cs[N] extends { readonly schema: infer S }\n ? S extends SchemaValidator<unknown, infer Out>\n ? Out\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>;\n"],"mappings":";AA+OA,SAAgB,aAA2C,KAAW;CACpE,OAAO;AACT"}
|
package/dist/auth.d.ts
CHANGED
package/dist/baerly.js
CHANGED
|
@@ -735,22 +735,22 @@ runBin(defineCommand({
|
|
|
735
735
|
description: "Vendorless document database CLI."
|
|
736
736
|
},
|
|
737
737
|
subCommands: {
|
|
738
|
-
deploy: () => import("./deploy-
|
|
739
|
-
doctor: () => import("./doctor-
|
|
740
|
-
inspect: () => import("./inspect-
|
|
741
|
-
export: () => import("./export-
|
|
742
|
-
cost: () => import("./cost-
|
|
738
|
+
deploy: () => import("./deploy-CrAbfgCq.js").then((m) => m.deploy),
|
|
739
|
+
doctor: () => import("./doctor-Db-hzPmE.js").then((m) => m.doctor),
|
|
740
|
+
inspect: () => import("./inspect-Bdbzvi-_.js").then((m) => m.inspect),
|
|
741
|
+
export: () => import("./export-Bhbz90-z.js").then((m) => m.exportCmd),
|
|
742
|
+
cost: () => import("./cost-CQt1YRkA.js").then((m) => m.cost),
|
|
743
743
|
admin: defineCommand({
|
|
744
744
|
meta: {
|
|
745
745
|
name: "admin",
|
|
746
746
|
description: "Operator commands — reconciliation and inspection."
|
|
747
747
|
},
|
|
748
748
|
subCommands: {
|
|
749
|
-
"rebuild-index": () => import("./rebuild-index-
|
|
750
|
-
dump: () => import("./dump-
|
|
751
|
-
restore: () => import("./restore-
|
|
752
|
-
fsck: () => import("./fsck-
|
|
753
|
-
usage: () => import("./usage-
|
|
749
|
+
"rebuild-index": () => import("./rebuild-index-DC_nR6wP.js").then((m) => m.rebuildIndexCmd),
|
|
750
|
+
dump: () => import("./dump-BYA55NLP.js").then((m) => m.dumpCmd),
|
|
751
|
+
restore: () => import("./restore-C6IcmLeA.js").then((m) => m.restoreCmd),
|
|
752
|
+
fsck: () => import("./fsck-CPPZWt9p.js").then((m) => m.fsckCmd),
|
|
753
|
+
usage: () => import("./usage-CLjirdD-.js").then((m) => m.usageCmd)
|
|
754
754
|
}
|
|
755
755
|
})
|
|
756
756
|
}
|