@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.
Files changed (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,480 @@
1
+ //#region packages/protocol/src/constants.d.ts
2
+ /**
3
+ * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
4
+ * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
5
+ * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
6
+ *
7
+ * - `"none"` — no header check; pin every request to `config.tenant`.
8
+ * For local dev, intranet, CLI tools — contexts where the network
9
+ * seam itself is the trust boundary.
10
+ * - `"shared-secret"` — bearer-token check; reads `SHARED_SECRET` from
11
+ * the runtime env and pins every request to `config.tenant`.
12
+ *
13
+ * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass
14
+ * this enum — pass a `Verifier` to the adapter factory's `verifier:`
15
+ * option instead.
16
+ */
17
+ declare const AUTH_CONFIG_VALUES: readonly ["none", "shared-secret"];
18
+ //#endregion
19
+ //#region packages/protocol/src/json.d.ts
20
+ /**
21
+ * The shape constraint for documents stored in a {@link Collection}.
22
+ *
23
+ * Plain JSON object: string-keyed; values are strings, numbers,
24
+ * booleans, nested {@link DocumentData}, or arrays of
25
+ * {@link DocumentValue}.
26
+ *
27
+ * The document **body** itself must be an object (not an array) —
28
+ * Baerly's writer is built on JSON Merge Patch (RFC 7396), which
29
+ * is only defined over object documents. Array *values* at any
30
+ * nested level are fine; per RFC 7396, an array in a patch
31
+ * replaces the target array wholesale (Baerly has no array-merge
32
+ * semantics).
33
+ */
34
+ type DocumentData = {
35
+ [x: string]: DocumentValue;
36
+ };
37
+ /**
38
+ * A single field value inside a {@link DocumentData}. The recursive
39
+ * type that backs {@link DocumentData}, also used by predicate and
40
+ * order-spec types in `@baerly/protocol/query`.
41
+ *
42
+ * Arrays are valid values; they are replaced (not merged) on patch.
43
+ */
44
+ type DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>;
45
+ type JSONObject = {
46
+ [x: string]: JSONValue;
47
+ };
48
+ type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;
49
+ //#endregion
50
+ //#region packages/protocol/src/query/wire.d.ts
51
+ /**
52
+ * Locked operator vocabulary. Methods on {@link PredicateBuilder}
53
+ * map 1:1 to these names; the validator rejects any other.
54
+ *
55
+ * `eq` — strict equality.
56
+ * `gt` / `gte` / `lt` / `lte` — scalar range. Bounds must be `string`
57
+ * or finite `number`. Type-mismatched actuals are always-miss.
58
+ * `in` — set membership. Empty array → `UnsatisfiablePredicate`.
59
+ */
60
+ type PredicateOpName = "eq" | "gt" | "gte" | "lt" | "lte" | "in";
61
+ /**
62
+ * One clause in a normalised predicate. `field` is a top-level key
63
+ * or a dotted path. `value` is an array iff `op === "in"`.
64
+ *
65
+ * `op: "eq"` on a primitive `value` is plain equality. The
66
+ * normaliser flattens nested literal sub-predicates
67
+ * (`{ assignee: { team: "x" } }`) to dotted-path `eq` clauses
68
+ * (`{op:"eq", field:"assignee.team", value:"x"}`), so an `eq`
69
+ * value at the wire level is never a nested non-primitive object
70
+ * — only callback-form `q.eq("nested", { ... })` could produce
71
+ * one, and that requires the type system to allow it at the call
72
+ * site.
73
+ */
74
+ interface PredicateClause {
75
+ readonly op: PredicateOpName;
76
+ readonly field: string;
77
+ readonly value: DocumentValue | ReadonlyArray<DocumentValue>;
78
+ }
79
+ /**
80
+ * Normalised predicate envelope. The wire form is a flat list of
81
+ * clauses; multiple clauses across all fields AND together. The
82
+ * empty wire `{ clauses: [] }` matches every document.
83
+ *
84
+ * Wire mirror on the HTTP surface: `?where=` carries the JSON
85
+ * encoding of this object. See `packages/server/API.md` for the
86
+ * literal example.
87
+ */
88
+ interface PredicateWire {
89
+ readonly clauses: ReadonlyArray<PredicateClause>;
90
+ }
91
+ //#endregion
92
+ //#region packages/protocol/src/indexes.d.ts
93
+ /**
94
+ * A secondary index declaration. Lives in `baerly.config.ts` under
95
+ * `collections.<name>.indexes[]` and is threaded through
96
+ * `Writer` via `WriterOptions.indexes`.
97
+ *
98
+ * Validated synchronously by `validateIndexDefinition`
99
+ * (in `@baerly/server`) at writer construction; an invalid def
100
+ * throws `BaerlyError{code: "SchemaError"}` before the first commit.
101
+ */
102
+ interface IndexDefinition {
103
+ /**
104
+ * Stable path-safe identifier. Must match `/^[a-z_][a-z0-9_]*$/`
105
+ * — used directly as a key segment under
106
+ * `<logPrefix>/index/<name>/...`.
107
+ */
108
+ readonly name: string;
109
+ /**
110
+ * Field name(s) to index on. `string` is a single-field index
111
+ * (today's read-path target). `readonly string[]` is composite —
112
+ * accepted by the key encoder but the predicate matcher only
113
+ * consults single-field index entries today.
114
+ *
115
+ * Top-level fields only — dotted-path `on` values throw
116
+ * `SchemaError` from `projectIndexValues`. A future change widens
117
+ * the projector to dotted paths (mirroring what
118
+ * `packages/server/src/query.ts` already does on the predicate
119
+ * side).
120
+ */
121
+ readonly on: string | readonly string[];
122
+ /**
123
+ * Optional sparse-projection filter (wire-form). When present, the
124
+ * writer emits index keys ONLY for docs that satisfy `predicate`
125
+ * under `matchesWire(predicate, body)`. Sparse indexes shrink the
126
+ * on-storage key set proportionally to filter selectivity — an
127
+ * index that matches ~1% of writes pays ~1% of the dense Class-A
128
+ * PUT cost.
129
+ *
130
+ * Operators allowed: `eq`, `gt`, `gte`, `lt`, `lte`, `in` — the
131
+ * locked {@link PredicateOpName} vocabulary. Range-shaped and
132
+ * `in`-shaped filters compose with the planner's cost-bias step
133
+ * via the implication checker, which proves whether a query
134
+ * predicate is contained in the filter's value range. A query
135
+ * that the filter's range / set strictly contains will route
136
+ * through the filtered index in preference to an unfiltered
137
+ * alternative.
138
+ *
139
+ * Wire shape example:
140
+ * `{ clauses: [{ op: "eq", field: "status", value: "open" }] }`.
141
+ *
142
+ * Planner cost-bias: a filtered index whose predicate is implied
143
+ * by the query predicate outranks an unfiltered alternative; an
144
+ * unfiltered index outranks a filtered one whose predicate is NOT
145
+ * implied (walking the smaller key set would miss matching docs).
146
+ */
147
+ readonly predicate?: PredicateWire;
148
+ }
149
+ //#endregion
150
+ //#region packages/protocol/src/schema.d.ts
151
+ /**
152
+ * Schema-validator adapter type for `Db.insert` / `Query.update` /
153
+ * `Collection.replace` boundary checks.
154
+ *
155
+ * Compatible with any library implementing StandardSchemaV1 — Zod
156
+ * 3.24+, Valibot 0.36+, ArkType 2.0+, and others
157
+ * (<https://standardschema.dev/>). The interface is pure-type:
158
+ * no runtime import, no peer dep.
159
+ *
160
+ * The runtime helper that consumes this shape
161
+ * (`validateOrThrow`) lives in `@baerly/server` —
162
+ * the type lives in protocol so cross-platform consumers (client,
163
+ * scaffold `baerly.config.ts`) can reference it without dragging
164
+ * Node-only server modules into their import graph.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * import { z } from "zod";
169
+ * import { defineConfig } from "@gusto/baerly-storage/config";
170
+ *
171
+ * const Ticket = z.object({
172
+ * _id: z.string(),
173
+ * status: z.enum(["open", "closed"]),
174
+ * title: z.string().min(1),
175
+ * });
176
+ *
177
+ * export default defineConfig({
178
+ * collections: {
179
+ * tickets: { schema: Ticket },
180
+ * },
181
+ * });
182
+ * ```
183
+ */
184
+ /**
185
+ * Subset of the StandardSchemaV1 contract Baerly consumes at the
186
+ * server boundary. The full spec lives at
187
+ * <https://standardschema.dev/>; we copy the `validate` shape locally
188
+ * because that's the only field the boundary calls, and inlining
189
+ * preserves the repo's "no new runtime deps" rule (the spec package
190
+ * is just this interface).
191
+ */
192
+ interface SchemaValidator<TInput = unknown, TOutput = TInput> {
193
+ readonly "~standard": {
194
+ readonly version: 1;
195
+ readonly vendor: string;
196
+ readonly validate: (value: unknown) => {
197
+ value: TOutput;
198
+ issues?: undefined;
199
+ } | {
200
+ issues: ReadonlyArray<SchemaIssue>;
201
+ } | Promise<{
202
+ value: TOutput;
203
+ issues?: undefined;
204
+ } | {
205
+ issues: ReadonlyArray<SchemaIssue>;
206
+ }>;
207
+ readonly types?: {
208
+ input: TInput;
209
+ output: TOutput;
210
+ };
211
+ };
212
+ }
213
+ /**
214
+ * One per-field validation failure. `path` is the validator-native
215
+ * shape — entries are either a bare `PropertyKey` (string / number /
216
+ * symbol) or a `{ key: PropertyKey }` segment, mirroring the live
217
+ * StandardSchemaV1 spec. `validateOrThrow` normalises both forms to
218
+ * `(string | number)[]` before raising the resulting
219
+ * `BaerlyError{code:"SchemaError"}`.
220
+ */
221
+ interface SchemaIssue {
222
+ readonly message: string;
223
+ /**
224
+ * Field path. Each entry is a string key, integer index, symbol
225
+ * (rare), or a `{ key: PropertyKey }` segment object — Zod 3.24+,
226
+ * Valibot 0.36+, ArkType 2.0+ etc. all emit the latter shape.
227
+ */
228
+ readonly path?: ReadonlyArray<PropertyKey | {
229
+ readonly key: PropertyKey;
230
+ }> | undefined;
231
+ }
232
+ //#endregion
233
+ //#region packages/protocol/src/app-config.d.ts
234
+ /**
235
+ * One collection's declarative config. Today `indexes` and `schema`
236
+ * are consumed; future tickets add `replica_identity` and lifecycle
237
+ * hooks.
238
+ */
239
+ interface CollectionDefinition {
240
+ /**
241
+ * Secondary indexes declared for this collection. Each declared
242
+ * index produces one zero-byte PUT per commit (when the indexed
243
+ * field is set on the doc) inside the same fence as the log
244
+ * entry and content body. See `./indexes.ts` for the key shape.
245
+ */
246
+ readonly indexes?: ReadonlyArray<IndexDefinition>;
247
+ /**
248
+ * Optional schema for this collection. When set, every server-side
249
+ * `insert` / `update` / `replace` validates the resulting post-image
250
+ * before committing — invalid input throws
251
+ * `BaerlyError{code:"SchemaError"}` carrying a `.issues` array of
252
+ * `{ path, message }` entries.
253
+ *
254
+ * Adapter: StandardSchemaV1 (see `./schema.ts`). Compatible with
255
+ * Zod 3.24+, Valibot 0.36+, ArkType 2.0+ today; any future library
256
+ * implementing the spec works without a code change here.
257
+ *
258
+ * `undefined` means no validation — every write proceeds as today
259
+ * (zero overhead, today's tests untouched).
260
+ *
261
+ * @remarks
262
+ * **`.nullable()` is not supported.** baerly's `DocumentValue` excludes
263
+ * `null` by design (see `packages/protocol/src/json.ts`). `null` is
264
+ * reserved as the JSON-merge-patch (RFC 7386) field-deletion sentinel
265
+ * in `update` patches. Use `.optional()` for absent values.
266
+ *
267
+ * Validation runs on the post-image: `update` and `replace` see the
268
+ * full doc, not just the patch. Failures throw
269
+ * `BaerlyError{ code: "SchemaError", issues: [...] }`.
270
+ */
271
+ readonly schema?: SchemaValidator;
272
+ }
273
+ /**
274
+ * The full `baerly.config.ts` runtime shape. Re-exported from
275
+ * `baerly-storage` and consumed by the day-1 `npm create baerly`
276
+ * scaffold + the `baerly admin rebuild-index` CLI.
277
+ */
278
+ interface BaerlyConfig {
279
+ /**
280
+ * Per-collection declarations, keyed by collection name. Required
281
+ * (declare `{}` when you have no collections yet) — this keeps the
282
+ * config interface from being structurally empty, which would
283
+ * trigger TypeScript's weak-type check when the adapter accepts
284
+ * the literal as `BaerlyWorkerOptions.config` / `BaerlyNodeOptions.config`.
285
+ */
286
+ readonly collections: Readonly<Record<string, CollectionDefinition>>;
287
+ }
288
+ /**
289
+ * Auth posture for the deployed app. REQUIRED on `BaerlyAppConfig`.
290
+ *
291
+ * - `"none"`: no header check; every request resolves to
292
+ * `config.tenant`. Use for local dev, intranet deployments, CLI
293
+ * tools — contexts where the network seam itself is the trust
294
+ * boundary. The adapter logs one startup line so the state is not
295
+ * silent.
296
+ * - `"shared-secret"`: bearer-token check; the adapter reads
297
+ * `SHARED_SECRET` from the runtime env and pins every request to
298
+ * `config.tenant`. Module init throws `BaerlyError("InvalidConfig", ...)`
299
+ * on first `fetch` if the env var is missing/empty.
300
+ *
301
+ * For custom verifiers (Cloudflare Access, JWT, SigV4, …), pass a
302
+ * `Verifier` directly to the adapter factory's `verifier:` option.
303
+ * The factory `verifier:` silently overrides `config.auth` when both
304
+ * are set — this is the "dev default in config, prod override via
305
+ * env" recipe.
306
+ *
307
+ * Field is required on `BaerlyAppConfig`. Omitting it causes both a
308
+ * TypeScript error at `defineConfig({...})` and (defensively) an
309
+ * `InvalidConfig` error at adapter module init.
310
+ *
311
+ * The literal values come from
312
+ * {@link AUTH_CONFIG_VALUES} so the runtime-only consumers (doctor,
313
+ * adapter) share the same source of truth.
314
+ */
315
+ type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];
316
+ /**
317
+ * `BaerlyAppConfig` extends `BaerlyConfig` with scaffold-flavoured
318
+ * deploy metadata (`target`, `domain`, `cloudflareAccess`, etc.).
319
+ *
320
+ * Exposed at `@gusto/baerly-storage/config`. Imported by the
321
+ * `baerly.config.ts` that `npm create baerly` emits, and by anyone
322
+ * who wants IDE/`tsgo` type inference on the full scaffold-aware
323
+ * config shape on top of the runtime `BaerlyConfig.collections` map.
324
+ *
325
+ * One `baerly.config.ts` carries both scaffold metadata (consumed by
326
+ * `baerly deploy` / `baerly doctor`) and the runtime schema
327
+ * (consumed by `Db.create`). The literal-pinned return type of
328
+ * {@link defineConfig} makes `collections` flow through to
329
+ * `Db.create<TConfig>` and `createBaerlyClient<TConfig>`.
330
+ */
331
+ interface BaerlyAppConfig extends BaerlyConfig {
332
+ /** Bucket-prefix for this baerly app. One bucket per app. */
333
+ readonly app: string;
334
+ /**
335
+ * Default tenant pin for `Verifier`s that don't derive a tenant
336
+ * from a claim. Production `Verifier`s (`bearerJwt`,
337
+ * `cloudflareAccess`) ignore this and derive `tenantPrefix` from
338
+ * the request.
339
+ */
340
+ readonly tenant: string;
341
+ /**
342
+ * Deploy target — `"cloudflare"` or `"node"`.
343
+ * Read by `baerly deploy` to dispatch the correct deploy command.
344
+ */
345
+ readonly target: "cloudflare" | "node";
346
+ /**
347
+ * Optional. Custom domain for the deployed service. Cloudflare:
348
+ * wired to the Worker as a route. Node: rendered into the
349
+ * Dockerfile's `EXPOSE` and the emitted readme.
350
+ */
351
+ readonly domain?: string | undefined;
352
+ /**
353
+ * Names of secrets the deployed runtime needs. `baerly deploy`
354
+ * and `baerly doctor` check each against the platform's secret
355
+ * store and warn (deploy) / report (doctor) when missing.
356
+ * Default treatment (when unset) is `["SHARED_SECRET"]` — matches
357
+ * the scaffolder's emitted Verifier wiring.
358
+ */
359
+ readonly requiredSecrets?: readonly string[];
360
+ /**
361
+ * Optional Cloudflare Access app config. When set, the production
362
+ * CF template prefers `cloudflareAccess()` as the `Verifier` and
363
+ * `baerly doctor --target=cloudflare` walks the CF Access app
364
+ * config to confirm the audience tag matches.
365
+ *
366
+ * - `teamDomain` — CF Access team domain, e.g. `"acme"`.
367
+ * - `audienceTag` — Application Audience (AUD) tag from the CF
368
+ * Access app, 64 lowercase-hex characters.
369
+ */
370
+ readonly cloudflareAccess?: {
371
+ readonly teamDomain: string;
372
+ readonly audienceTag: string;
373
+ };
374
+ /**
375
+ * Optional observability overrides. The templates already
376
+ * read `LOG_LEVEL` from the runtime env; this field is a
377
+ * typed-config alternative for deployments that prefer to pin
378
+ * defaults in source. See `docs/guide/observability.md` for the
379
+ * canonical-line shape and `docs/contributing/conventions/observability.md` for
380
+ * the one-canonical-line-per-unit-of-work rule.
381
+ *
382
+ * - `level` — lowest record level reaching the sink. Falls back
383
+ * to the `LOG_LEVEL` env var, then to `"info"`.
384
+ */
385
+ readonly observability?: {
386
+ readonly level?: "debug" | "info" | "warn" | "error";
387
+ };
388
+ /**
389
+ * Auth posture. See {@link AuthConfig} for the full per-value
390
+ * semantics, the failure modes, and the "dev default, prod override"
391
+ * recipe. Field is required — omission fails typecheck and (for
392
+ * adapters that didn't supply a `verifier:` override) throws
393
+ * `BaerlyError("InvalidConfig", ...)` at first request.
394
+ */
395
+ readonly auth: AuthConfig;
396
+ }
397
+ /**
398
+ * Identity helper that pins the config's TypeScript shape so IDEs
399
+ * surface autocomplete and `tsgo --noEmit` catches typos at write
400
+ * time. Returns its input verbatim — no runtime transformation.
401
+ *
402
+ * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`
403
+ * (the shape `npm create baerly` emits, which carries `app`,
404
+ * `tenant`, `target` deploy metadata) and one for the runtime
405
+ * `BaerlyConfig` shape (just `collections`, used by tests and by
406
+ * apps that wire deploy metadata in some other way). Both preserve
407
+ * the literal shape of `cfg` via `<const C>` so `CollectionNames<C>`
408
+ * and `RowOf<C, N>` resolve to literal unions.
409
+ */
410
+ declare function defineConfig<const C extends BaerlyAppConfig>(cfg: C): C;
411
+ declare function defineConfig<const C extends BaerlyConfig>(cfg: C): C;
412
+ /**
413
+ * Sentinel `BaerlyConfig` used as the default `TConfig` parameter
414
+ * by consumers (`Db<TConfig>`, `BaerlyClient<TConfig>`). Setting
415
+ * `collections` to `Record<string, CollectionDefinition>` makes
416
+ * `CollectionNames<UnboundConfig>` widen to `string`, so the single
417
+ * typed accessor `db.collection<N extends CollectionNames<TConfig>>(name: N)`
418
+ * still resolves for kernel-internal paths (which carry no bound
419
+ * config) — those callers see `name: string` and the row type
420
+ * defaults to `DocumentData` via {@link RowOf}'s `Record<string, unknown>`
421
+ * fallback. Consumers who bind a config via {@link defineConfig}
422
+ * narrow `CollectionNames<TConfig>` to a literal union and lose the
423
+ * string-typo accepting behaviour, which is the design intent.
424
+ */
425
+ type UnboundConfig = {
426
+ readonly collections: Record<string, CollectionDefinition>;
427
+ };
428
+ /**
429
+ * Set of declared collection names on a `BaerlyConfig`, as a string
430
+ * union. Resolves to `never` when no `collections` are declared
431
+ * (notably for `UnboundConfig`), which the typed `Db` / client
432
+ * overloads use to disable narrowing for unbound consumers.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * const config = defineConfig({
437
+ * collections: {
438
+ * tickets: { schema: TicketSchema },
439
+ * audits: {},
440
+ * },
441
+ * });
442
+ * type Names = CollectionNames<typeof config>; // "tickets" | "audits"
443
+ * ```
444
+ */
445
+ type CollectionNames<C extends BaerlyConfig> = C extends {
446
+ readonly collections: infer Cs;
447
+ } ? Extract<keyof Cs, string> : never;
448
+ /**
449
+ * Row type for collection `N` on config `C`. Resolves to the
450
+ * `StandardSchemaV1` output type of `C["collections"][N]["schema"]`
451
+ * when one is declared; otherwise falls back to
452
+ * `Record<string, unknown>`.
453
+ *
454
+ * The fallback is intentionally wider than the protocol's
455
+ * `DocumentData`. Downstream call sites that need
456
+ * `DocumentData` (e.g. `Collection<T extends DocumentData>`)
457
+ * apply the intersection at their own seam — keeping that
458
+ * constraint local to the consumer keeps THIS file independent of
459
+ * `@baerly/protocol/src/json.ts`.
460
+ *
461
+ * @example
462
+ * ```ts
463
+ * const config = defineConfig({
464
+ * collections: {
465
+ * tickets: { schema: TicketSchema },
466
+ * audits: {},
467
+ * },
468
+ * });
469
+ * type Ticket = RowOf<typeof config, "tickets">; // z.infer<typeof TicketSchema>
470
+ * type Audit = RowOf<typeof config, "audits">; // Record<string, unknown>
471
+ * ```
472
+ */
473
+ type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {
474
+ readonly collections: infer Cs;
475
+ } ? N extends keyof Cs ? Cs[N] extends {
476
+ readonly schema: infer S;
477
+ } ? S extends SchemaValidator<unknown, infer Out> ? Out : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;
478
+ //#endregion
479
+ 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-Cb5dO2s9.d.ts.map
@@ -0,0 +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-Cb5dO2s9.js";
2
+ export { AuthConfig, BaerlyAppConfig, BaerlyConfig, CollectionDefinition, CollectionNames, type DocumentData, type DocumentValue, RowOf, UnboundConfig, defineConfig };
@@ -0,0 +1,8 @@
1
+ //#region packages/protocol/src/app-config.ts
2
+ function defineConfig(cfg) {
3
+ return cfg;
4
+ }
5
+ //#endregion
6
+ export { defineConfig };
7
+
8
+ //# sourceMappingURL=app-config.js.map
@@ -0,0 +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"}