@lunora/values 1.0.0-alpha.1 → 1.0.0-alpha.10

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/dist/index.d.ts CHANGED
@@ -1,11 +1,17 @@
1
+ import { LunoraError } from '@lunora/errors';
1
2
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
3
  type ValidationPath = ReadonlyArray<number | string>;
3
4
  /**
4
- * Thrown by `validator.parse` (or returned inside `safeParse`) when input does
5
- * not match the validator's shape. `path` walks from the root to the offending
6
- * value, e.g. `["users", 0, "email"]`.
7
- */
8
- declare class ValidationError extends Error {
5
+ * Thrown by `validator.parse` (or returned inside `safeParse`) when input does
6
+ * not match the validator's shape. `path` walks from the root to the offending
7
+ * value, e.g. `["users", 0, "email"]`.
8
+ *
9
+ * A `LunoraError` subclass: carries `code: "VALIDATION_ERROR"` and `status: 400`
10
+ * so the runtime/DO transport mappers surface it structurally (a request that
11
+ * fails validation is a 400), while keeping the `name: "ValidationError"` and the
12
+ * `path`/`expected`/`received` diagnostics.
13
+ */
14
+ declare class ValidationError extends LunoraError {
9
15
  readonly path: ValidationPath;
10
16
  readonly expected: string;
11
17
  readonly received: string;
@@ -16,35 +22,43 @@ declare class ValidationError extends Error {
16
22
  });
17
23
  }
18
24
  /**
19
- * Render a short, diagnostic description of a runtime value for the `received`
20
- * field of a {@link ValidationError}. Primitives carry their concrete (length-
21
- * capped) literal so messages distinguish `string "7"` from `number 7`;
22
- * non-plain objects carry their constructor name (e.g. `Date`) so a class
23
- * instance is not flattened to a bare `"object"`.
24
- */
25
- declare const describeValue: (value: unknown) => string;
25
+ * Render a short, diagnostic description of a runtime value for the `received`
26
+ * field of a {@link ValidationError}. Primitives carry their concrete (length-
27
+ * capped) literal so messages distinguish `string "7"` from `number 7`;
28
+ * non-plain objects carry their constructor name (e.g. `Date`) so a class
29
+ * instance is not flattened to a bare `"object"`.
30
+ *
31
+ * Pass `{ literal: false }` to suppress the concrete primitive literal and
32
+ * return only the type tag (`"string"`, `"number"`, `"bigint"`, …). This is used
33
+ * on `.check()` refinement failures — where the value already passed its type
34
+ * check — so a secret-bearing field (password, token) never surfaces its value
35
+ * in the `ValidationError.message`/`received` that goes to the wire and logs.
36
+ */
37
+ declare const describeValue: (value: unknown, options?: {
38
+ literal?: boolean;
39
+ }) => string;
26
40
  declare const formatPath: (path: ValidationPath) => string;
27
41
  /** Branded id type, e.g. `Id&lt;"users">`. */
28
42
  type Id<TableName extends string> = string & {
29
43
  readonly __table: TableName;
30
44
  };
31
45
  /**
32
- * A JSON Schema fragment (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally
33
- * a loose bag — a `.check()`/`.meta()` caller contributes keywords like
34
- * `minLength`/`pattern`/`minimum` that `toJsonSchema` shallow-merges onto the
35
- * node for the enclosing validator. Mirrors the `JsonSchema` shape exported by
36
- * `./to-json-schema`; kept structurally identical and local so `v.ts` never
37
- * imports the converter and the two files stay decoupled.
38
- */
46
+ * A JSON Schema fragment (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally
47
+ * a loose bag — a `.check()`/`.meta()` caller contributes keywords like
48
+ * `minLength`/`pattern`/`minimum` that `toJsonSchema` shallow-merges onto the
49
+ * node for the enclosing validator. Mirrors the `JsonSchema` shape exported by
50
+ * `./to-json-schema`; kept structurally identical and local so `v.ts` never
51
+ * imports the converter and the two files stay decoupled.
52
+ */
39
53
  interface JsonSchemaFragment {
40
54
  [keyword: string]: unknown;
41
55
  }
42
56
  /**
43
- * Options for a {@link Validator.check} refinement. Lets a predicate carry both
44
- * a human-facing `message` and an introspectable JSON Schema `schema` fragment
45
- * (e.g. `{ minLength: 1 }`) so the constraint flows into `toJsonSchema`. The
46
- * legacy `.check(pred, "message")` string form remains supported.
47
- */
57
+ * Options for a {@link Validator.check} refinement. Lets a predicate carry both
58
+ * a human-facing `message` and an introspectable JSON Schema `schema` fragment
59
+ * (e.g. `{ minLength: 1 }`) so the constraint flows into `toJsonSchema`. The
60
+ * legacy `.check(pred, "message")` string form remains supported.
61
+ */
48
62
  interface CheckOptions {
49
63
  /** Failure message thrown on the `ValidationError` (default `"value matching refinement"`). */
50
64
  message?: string;
@@ -52,10 +66,10 @@ interface CheckOptions {
52
66
  schema?: JsonSchemaFragment;
53
67
  }
54
68
  /**
55
- * Options for {@link Validator.meta} — pure metadata with no runtime parsing
56
- * effect, used to enrich the emitted JSON Schema node (description + constraint
57
- * keywords) without attaching a predicate.
58
- */
69
+ * Options for {@link Validator.meta} — pure metadata with no runtime parsing
70
+ * effect, used to enrich the emitted JSON Schema node (description + constraint
71
+ * keywords) without attaching a predicate.
72
+ */
59
73
  interface MetaOptions {
60
74
  /** A human description merged onto this validator's JSON Schema node. */
61
75
  description?: string;
@@ -63,36 +77,36 @@ interface MetaOptions {
63
77
  schema?: JsonSchemaFragment;
64
78
  }
65
79
  /**
66
- * Runtime "kind" tag attached to every validator. Codegen and reflective tools
67
- * use this to inspect the shape without crawling the closure.
68
- */
69
- type ValidatorKind = "any" | "array" | "bigint" | "boolean" | "bytes" | "date" | "from" | "id" | "literal" | "null" | "number" | "object" | "optional" | "record" | "storage" | "string" | "timestamp" | "union";
80
+ * Runtime "kind" tag attached to every validator. Codegen and reflective tools
81
+ * use this to inspect the shape without crawling the closure.
82
+ */
83
+ type ValidatorKind = "any" | "array" | "bigint" | "boolean" | "bytes" | "date" | "from" | "geoPoint" | "id" | "literal" | "null" | "number" | "object" | "optional" | "record" | "storage" | "string" | "timestamp" | "union";
70
84
  interface Validator<T = unknown> extends StandardSchemaV1<T, T> {
71
85
  readonly __type: T;
72
86
  /**
73
- * Attach a refinement predicate. The returned validator parses with the
74
- * original rules first; if the result satisfies `predicate` it passes
75
- * through, otherwise it throws a {@link ValidationError} carrying
76
- * `message` (default: `"value matching refinement"`). Multiple `.check()`
77
- * calls chain — every predicate must return true.
78
- *
79
- * The second argument may be a plain message string (legacy form) or a
80
- * {@link CheckOptions} object that additionally carries a JSON Schema
81
- * `schema` fragment (e.g. `{ minLength: 1 }`) reflected by `toJsonSchema`.
82
- *
83
- * Works in any context — argument validators, column validators, or
84
- * standalone — so it can encode invariants like
85
- * `v.number().check(n => n >= 0)` or
86
- * `v.string().check(s => s.length > 0, { message: "non-empty", schema: { minLength: 1 } })`.
87
- */
87
+ * Attach a refinement predicate. The returned validator parses with the
88
+ * original rules first; if the result satisfies `predicate` it passes
89
+ * through, otherwise it throws a {@link ValidationError} carrying
90
+ * `message` (default: `"value matching refinement"`). Multiple `.check()`
91
+ * calls chain — every predicate must return true.
92
+ *
93
+ * The second argument may be a plain message string (legacy form) or a
94
+ * {@link CheckOptions} object that additionally carries a JSON Schema
95
+ * `schema` fragment (e.g. `{ minLength: 1 }`) reflected by `toJsonSchema`.
96
+ *
97
+ * Works in any context — argument validators, column validators, or
98
+ * standalone — so it can encode invariants like
99
+ * `v.number().check(n => n >= 0)` or
100
+ * `v.string().check(s => s.length > 0, { message: "non-empty", schema: { minLength: 1 } })`.
101
+ */
88
102
  check: (predicate: (value: T) => boolean, options?: CheckOptions | string) => Validator<T>;
89
103
  readonly kind: ValidatorKind;
90
104
  /**
91
- * Attach pure metadata (description + JSON Schema constraint fragment) with
92
- * no effect on runtime parsing. The fragment is shallow-merged onto this
93
- * validator's emitted JSON Schema node, composing with any `.check()`
94
- * `schema` fragments (later wins on conflicting keys).
95
- */
105
+ * Attach pure metadata (description + JSON Schema constraint fragment) with
106
+ * no effect on runtime parsing. The fragment is shallow-merged onto this
107
+ * validator's emitted JSON Schema node, composing with any `.check()`
108
+ * `schema` fragments (later wins on conflicting keys).
109
+ */
96
110
  meta: (options: MetaOptions) => Validator<T>;
97
111
  parse: (value: unknown) => T;
98
112
  safeParse: (value: unknown) => {
@@ -106,10 +120,10 @@ interface Validator<T = unknown> extends StandardSchemaV1<T, T> {
106
120
  /** Extract the TS type a validator describes (the **select** type). */
107
121
  type Infer<V> = V extends Validator<infer T> ? T : never;
108
122
  /**
109
- * Column constraints/defaults collected from the `v.*` modifier chain used
110
- * inside `defineTable`. Inert in argument position. Persisted on the
111
- * validator's internal `_meta.column` and mirrored into codegen IR.
112
- */
123
+ * Column constraints/defaults collected from the `v.*` modifier chain used
124
+ * inside `defineTable`. Inert in argument position. Persisted on the
125
+ * validator's internal `_meta.column` and mirrored into codegen IR.
126
+ */
113
127
  interface ColumnMeta {
114
128
  /** `.$defaultFn(fn)` — default factory; field is optional on insert. */
115
129
  defaultFn?: () => unknown;
@@ -120,24 +134,24 @@ interface ColumnMeta {
120
134
  /** `.$onUpdateFn(fn)` — recomputed on every patch/replace. */
121
135
  onUpdateFn?: () => unknown;
122
136
  /**
123
- * `.serverDefault(fn)` — a SERVER-trusted value factory. Unlike
124
- * `.$defaultFn` (which only fills an absent field), this runs on every
125
- * insert/update and SILENTLY OVERWRITES any client-supplied value with
126
- * `fn({ auth })`, so the column is never client-controllable (e.g.
127
- * `ownerId`/`tenantId` stamped from `auth.userId`). Field is optional on
128
- * insert. The factory runs server-side with the resolved request auth.
129
- */
137
+ * `.serverDefault(fn)` — a SERVER-trusted value factory. Unlike
138
+ * `.$defaultFn` (which only fills an absent field), this runs on every
139
+ * insert/update and SILENTLY OVERWRITES any client-supplied value with
140
+ * `fn({ auth })`, so the column is never client-controllable (e.g.
141
+ * `ownerId`/`tenantId` stamped from `auth.userId`). Field is optional on
142
+ * insert. The factory runs server-side with the resolved request auth.
143
+ */
130
144
  serverDefault?: (context: ServerDefaultContext) => unknown;
131
145
  /** `.unique()` — synthesizes a UNIQUE index. */
132
146
  unique?: boolean;
133
147
  }
134
148
  /**
135
- * Context handed to a `.serverDefault(fn)` factory at write time. Carries the
136
- * resolved request identity so a column can be stamped from the caller
137
- * (`auth.userId`) rather than trusted from the client. Structurally mirrors the
138
- * `auth` slice of the server's procedure context without depending on
139
- * `@lunora/server`.
140
- */
149
+ * Context handed to a `.serverDefault(fn)` factory at write time. Carries the
150
+ * resolved request identity so a column can be stamped from the caller
151
+ * (`auth.userId`) rather than trusted from the client. Structurally mirrors the
152
+ * `auth` slice of the server's procedure context without depending on
153
+ * `@lunora/server`.
154
+ */
141
155
  interface ServerDefaultContext {
142
156
  readonly auth: {
143
157
  /** The raw identity claims, or `null` for the anonymous/no-resolver case. */
@@ -147,9 +161,9 @@ interface ServerDefaultContext {
147
161
  };
148
162
  }
149
163
  /**
150
- * Phantom carrier of a column's select/insert types. Never present at runtime;
151
- * `defineTable` reads it to derive `$inferSelect` / `$inferInsert`.
152
- */
164
+ * Phantom carrier of a column's select/insert types. Never present at runtime;
165
+ * `defineTable` reads it to derive `$inferSelect` / `$inferInsert`.
166
+ */
153
167
  interface Column<TSelect, TInsert> {
154
168
  /** Phantom carrier — type-only, never present at runtime. */
155
169
  readonly __column: {
@@ -158,11 +172,11 @@ interface Column<TSelect, TInsert> {
158
172
  };
159
173
  }
160
174
  /**
161
- * A {@link Validator} carrying the chainable column-modifier API. The factories
162
- * (`v.string()`, …) return this so modifiers are available inside `defineTable`.
163
- * `TSelect` is the read type; `TInsert` is the write type (modifiers may make it
164
- * `| undefined`, marking the field optional on insert).
165
- */
175
+ * A {@link Validator} carrying the chainable column-modifier API. The factories
176
+ * (`v.string()`, …) return this so modifiers are available inside `defineTable`.
177
+ * `TSelect` is the read type; `TInsert` is the write type (modifiers may make it
178
+ * `| undefined`, marking the field optional on insert).
179
+ */
166
180
  interface ColumnValidator<TSelect, TInsert> extends Column<TSelect, TInsert>, Validator<TSelect> {
167
181
  /** Default factory applied in the write layer; field becomes optional on insert. */
168
182
  $defaultFn: (function_: () => TSelect) => ColumnValidator<TSelect, TInsert | undefined>;
@@ -179,20 +193,20 @@ interface ColumnValidator<TSelect, TInsert> extends Column<TSelect, TInsert>, Va
179
193
  /** Allow SQL NULL — widens the select type to `T | null`. */
180
194
  nullable: () => ColumnValidator<null | TSelect, null | TInsert>;
181
195
  /**
182
- * Stamp this column SERVER-side from the request auth on every write,
183
- * overwriting any client-supplied value. The field becomes optional on
184
- * insert (the server fills it). Use for owner/tenant columns that must never
185
- * be client-controllable — e.g. `v.string().serverDefault(({ auth }) => auth.userId)`.
186
- */
196
+ * Stamp this column SERVER-side from the request auth on every write,
197
+ * overwriting any client-supplied value. The field becomes optional on
198
+ * insert (the server fills it). Use for owner/tenant columns that must never
199
+ * be client-controllable — e.g. `v.string().serverDefault(({ auth }) => auth.userId)`.
200
+ */
187
201
  serverDefault: (function_: (context: ServerDefaultContext) => TSelect) => ColumnValidator<TSelect, TInsert | undefined>;
188
202
  /** Enforce a UNIQUE constraint (synthesizes a unique index). */
189
203
  unique: () => ColumnValidator<TSelect, TInsert>;
190
204
  }
191
205
  /**
192
- * A time-valued {@link ColumnValidator} (epoch milliseconds). Adds
193
- * {@link TimestampColumnValidator.defaultNow} so the field can default to the
194
- * insert-time clock.
195
- */
206
+ * A time-valued {@link ColumnValidator} (epoch milliseconds). Adds
207
+ * {@link TimestampColumnValidator.defaultNow} so the field can default to the
208
+ * insert-time clock.
209
+ */
196
210
  interface TimestampColumnValidator extends ColumnValidator<number, number> {
197
211
  /** Default to the current epoch-ms (`Date.now()`) at insert time; field becomes optional on insert. */
198
212
  defaultNow: () => ColumnValidator<number, number | undefined>;
@@ -202,13 +216,13 @@ type InferSelect<V> = V extends Validator<infer T> ? T : never;
202
216
  /** The type a validator/column accepts on **insert** (writes). */
203
217
  type InferInsert<V> = V extends Column<unknown, infer I> ? I : V extends Validator<infer T> ? T : never;
204
218
  /** Derive the read shape of a table's column map. */
205
- type SelectShape<S extends Record<string, Validator>> = { [K in keyof S]: InferSelect<S[K]> };
219
+ type SelectShape<S extends Record<string, Validator>> = { [K in keyof S]: InferSelect<S[K]>; };
206
220
  /**
207
- * Derive the write shape of a table's column map. Columns whose insert type
208
- * includes `undefined` (via `.default()` / `.$defaultFn()` / `v.optional`)
209
- * become optional keys.
210
- */
211
- type InsertShape<S extends Record<string, Validator>> = { [K in keyof S as undefined extends InferInsert<S[K]> ? K : never]?: Exclude<InferInsert<S[K]>, undefined> } & { [K in keyof S as undefined extends InferInsert<S[K]> ? never : K]: InferInsert<S[K]> };
221
+ * Derive the write shape of a table's column map. Columns whose insert type
222
+ * includes `undefined` (via `.default()` / `.$defaultFn()` / `v.optional`)
223
+ * become optional keys.
224
+ */
225
+ type InsertShape<S extends Record<string, Validator>> = { [K in keyof S as undefined extends InferInsert<S[K]> ? K : never]?: Exclude<InferInsert<S[K]>, undefined>; } & { [K in keyof S as undefined extends InferInsert<S[K]> ? never : K]: InferInsert<S[K]>; };
212
226
  declare const string: () => ColumnValidator<string, string>;
213
227
  declare const number: () => ColumnValidator<number, number>;
214
228
  /** Epoch-millisecond timestamp (`number`). Pair with `.defaultNow()` for an insert-time clock. */
@@ -221,68 +235,97 @@ declare const nullValidator: () => ColumnValidator<null, null>;
221
235
  declare const bytes: () => ColumnValidator<ArrayBuffer, ArrayBuffer>;
222
236
  declare const id: <TableName extends string>(tableName: TableName) => ColumnValidator<Id<TableName>, Id<TableName>>;
223
237
  /**
224
- * A reference to a stored R2 object: the column holds the object's **key** (a
225
- * string), the same key `@lunora/storage` puts/gets by. Functionally it parses
226
- * like `v.string()`, but the distinct `"storage"` kind lets codegen and the
227
- * studio join the data model to R2 — the file browser uses it to show which
228
- * record owns a file and to flag orphaned objects no row references. The
229
- * optional `bucket` names the typed bucket the key lives in (for app-context
230
- * signed URLs); omit it for the app's default bucket.
231
- */
238
+ * A reference to a stored R2 object: the column holds the object's **key** (a
239
+ * string), the same key `@lunora/storage` puts/gets by. Functionally it parses
240
+ * like `v.string()`, but the distinct `"storage"` kind lets codegen and the
241
+ * studio join the data model to R2 — the file browser uses it to show which
242
+ * record owns a file and to flag orphaned objects no row references. The
243
+ * optional `bucket` names the typed bucket the key lives in (for app-context
244
+ * signed URLs); omit it for the app's default bucket.
245
+ */
232
246
  declare const storage: (bucket?: string) => ColumnValidator<string, string>;
247
+ /**
248
+ * A geographic point — latitude/longitude in decimal degrees (WGS84). The value
249
+ * a `v.geoPoint()` column reads/writes. Stored as a JSON object alongside the
250
+ * row; a `.geoIndex(name, { field })` on the table maintains a geohash companion
251
+ * so `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` can answer
252
+ * proximity/bounding-box reads.
253
+ */
254
+ interface GeoPoint {
255
+ /** Latitude in decimal degrees, `-90 … 90`. */
256
+ lat: number;
257
+ /** Longitude in decimal degrees, `-180 … 180`. */
258
+ lng: number;
259
+ }
260
+ /**
261
+ * A latitude/longitude point (WGS84 decimal degrees). Parses an object with
262
+ * finite `lat` ∈ `[-90, 90]` and `lng` ∈ `[-180, 180]`; any other shape or an
263
+ * out-of-range coordinate throws a {@link ValidationError}. Pair with a table's
264
+ * `.geoIndex(name, { field })` to enable `near` / `within` reads.
265
+ */
266
+ declare const geoPoint: () => ColumnValidator<GeoPoint, GeoPoint>;
233
267
  declare const literal: <T extends bigint | boolean | number | string | null>(literalValue: T) => ColumnValidator<T, T>;
234
268
  declare const array: <V extends Validator>(inner: V) => ColumnValidator<Infer<V>[], Infer<V>[]>;
269
+ /**
270
+ * Split a value-type map into optional + required keys: any member whose value
271
+ * type includes `undefined` becomes an optional key. The single optionality rule
272
+ * shared by object-shape inference ({@link ObjectShapeType}) and args-map
273
+ * inference (`InferValidatorMap` in `./validator-map`), so the two can never
274
+ * drift. (`InsertShape` stays separate — it additionally `Exclude`s `undefined`
275
+ * from the optional value, a deliberate insert-type difference.)
276
+ */
277
+ type OptionalizeShape<M> = { [K in keyof M as undefined extends M[K] ? K : never]?: M[K]; } & { [K in keyof M as undefined extends M[K] ? never : K]: M[K]; };
235
278
  type ObjectShape = Record<string, Validator>;
236
- type ObjectShapeType<S extends ObjectShape> = { [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]> } & { [K in keyof S as undefined extends Infer<S[K]> ? never : K]: Infer<S[K]> };
279
+ type ObjectShapeType<S extends ObjectShape> = OptionalizeShape<{ [K in keyof S]: Infer<S[K]>; }>;
237
280
  declare const objectValidator: <S extends ObjectShape>(shape: S) => ColumnValidator<ObjectShapeType<S>, ObjectShapeType<S>>;
238
281
  declare const record: <K extends Validator<string>, V extends Validator>(keyValidator: K, valueValidator: V) => ColumnValidator<Record<Infer<K>, Infer<V>>, Record<Infer<K>, Infer<V>>>;
239
282
  declare const union: <Vs extends ReadonlyArray<Validator>>(...members: Vs) => ColumnValidator<Infer<Vs[number]>, Infer<Vs[number]>>;
240
283
  declare const optional: <V extends Validator>(inner: V) => ColumnValidator<Infer<V> | undefined, Infer<V> | undefined>;
241
284
  declare const any: () => ColumnValidator<unknown, unknown>;
242
285
  /**
243
- * Infer the output type of a Standard Schema v1 object. When the schema omits
244
- * `~standard.types` (it is optional in the spec), falls back to `unknown` so
245
- * callers always get a usable type rather than `never`.
246
- */
286
+ * Infer the output type of a Standard Schema v1 object. When the schema omits
287
+ * `~standard.types` (it is optional in the spec), falls back to `unknown` so
288
+ * callers always get a usable type rather than `never`.
289
+ */
247
290
  type InferStandardOutput<S extends StandardSchemaV1> = S["~standard"]["types"] extends {
248
291
  output: infer O;
249
292
  } ? O : unknown;
250
293
  /**
251
- * Wrap any Standard Schema v1 validator (`zod`, `valibot`, `arktype`, …) so it
252
- * can be used as an **args** validator in `query`/`mutation`/`action`. The
253
- * wrapped validator's output type is inferred from `~standard.types.output`
254
- * when declared; falls back to `unknown` when the schema omits the types field.
255
- *
256
- * **Args-only.** `v.from(...)` validators must not be used as table columns —
257
- * `defineTable` checks the `kind` and throws a clear error if you try.
258
- *
259
- * **Sync-only.** Standard Schema allows async `validate`; Lunora args
260
- * validation is synchronous and throws when a Promise is returned.
261
- */
294
+ * Wrap any Standard Schema v1 validator (`zod`, `valibot`, `arktype`, …) so it
295
+ * can be used as an **args** validator in `query`/`mutation`/`action`. The
296
+ * wrapped validator's output type is inferred from `~standard.types.output`
297
+ * when declared; falls back to `unknown` when the schema omits the types field.
298
+ *
299
+ * **Args-only.** `v.from(...)` validators must not be used as table columns —
300
+ * `defineTable` checks the `kind` and throws a clear error if you try.
301
+ *
302
+ * **Sync-only.** Standard Schema allows async `validate`; Lunora args
303
+ * validation is synchronous and throws when a Promise is returned.
304
+ */
262
305
  declare const from: <S extends StandardSchemaV1>(schema: S) => ColumnValidator<InferStandardOutput<S>, InferStandardOutput<S>>;
263
306
  /**
264
- * True when `validator` is `v.from(...)` or structurally wraps one through
265
- * `v.optional` / `v.array` / `v.object` / `v.record` / `v.union`. `defineTable`
266
- * uses it to reject Standard-Schema-backed validators anywhere in a column —
267
- * not just at the top level — since they are args-only and have no SQL column
268
- * type. The nested children live on the validator's `_meta` (`inner`, `shape`,
269
- * `members`, `keyValidator`/`valueValidator`) and are themselves validators.
270
- */
307
+ * True when `validator` is `v.from(...)` or structurally wraps one through
308
+ * `v.optional` / `v.array` / `v.object` / `v.record` / `v.union`. `defineTable`
309
+ * uses it to reject Standard-Schema-backed validators anywhere in a column —
310
+ * not just at the top level — since they are args-only and have no SQL column
311
+ * type. The nested children live on the validator's `_meta` (`inner`, `shape`,
312
+ * `members`, `keyValidator`/`valueValidator`) and are themselves validators.
313
+ */
271
314
  declare const isOrWrapsFromValidator: (validator: Validator) => boolean;
272
315
  /**
273
- * The inner validator wrapped by `v.optional(inner)`, or `undefined` for any
274
- * other validator. The nested child lives on the validator's internal `_meta`
275
- * bag; this accessor keeps that knowledge inside `@lunora/values` (the package
276
- * that owns validator internals) so consumers don't reach into `_meta`
277
- * themselves. Used by `@lunora/server`'s `defineEnv` to coerce through a leading
278
- * `v.optional(...)`.
279
- * @returns The inner validator if `v.optional(...)`, otherwise `undefined`.
280
- */
316
+ * The inner validator wrapped by `v.optional(inner)`, or `undefined` for any
317
+ * other validator. The nested child lives on the validator's internal `_meta`
318
+ * bag; this accessor keeps that knowledge inside `@lunora/values` (the package
319
+ * that owns validator internals) so consumers don't reach into `_meta`
320
+ * themselves. Used by `@lunora/server`'s `defineEnv` to coerce through a leading
321
+ * `v.optional(...)`.
322
+ * @returns The inner validator if `v.optional(...)`, otherwise `undefined`.
323
+ */
281
324
  declare const optionalInner: (validator: Validator) => Validator | undefined;
282
325
  /**
283
- * Validator/codec namespace. Each factory returns a {@link Validator} with a
284
- * runtime `parse`/`safeParse` plus a phantom `__type` field for inference.
285
- */
326
+ * Validator/codec namespace. Each factory returns a {@link Validator} with a
327
+ * runtime `parse`/`safeParse` plus a phantom `__type` field for inference.
328
+ */
286
329
  declare const v: {
287
330
  any: typeof any;
288
331
  array: typeof array;
@@ -291,6 +334,7 @@ declare const v: {
291
334
  bytes: typeof bytes;
292
335
  date: typeof date;
293
336
  from: typeof from;
337
+ geoPoint: typeof geoPoint;
294
338
  id: typeof id;
295
339
  literal: typeof literal;
296
340
  null: typeof nullValidator;
@@ -304,35 +348,35 @@ declare const v: {
304
348
  union: typeof union;
305
349
  };
306
350
  /**
307
- * A JSON Schema node (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally a
308
- * loose bag — Lunora only emits a known subset, but consumers (OpenAPI/OpenRPC
309
- * builders, Swagger UI, form generators) treat it as an opaque schema object.
310
- */
351
+ * A JSON Schema node (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally a
352
+ * loose bag — Lunora only emits a known subset, but consumers (OpenAPI/OpenRPC
353
+ * builders, Swagger UI, form generators) treat it as an opaque schema object.
354
+ */
311
355
  interface JsonSchema {
312
356
  [keyword: string]: unknown;
313
357
  }
314
358
  /**
315
- * Structural reader over a validator-like node. The shared mapping algorithm
316
- * ({@link jsonSchemaFromNode}) is parameterized by this interface so the same
317
- * switch/recursion serves both inputs Lunora maps to JSON Schema: the runtime
318
- * `@lunora/values` validator (children + metadata live on `_meta`), and the
319
- * build-time validator IR consumed by codegen (children are plain fields, with
320
- * no runtime metadata — so `constraints`/`isNullable` may be inert there).
321
- *
322
- * A reader normalizes a `TNode` to the small set of children/leaves the mapper
323
- * recurses over. Composite accessors (`inner`/`shape`/`members`/`valueChild`)
324
- * return the same `TNode` type so the mapper can recurse uniformly; leaf concerns
325
- * that differ between the two sources — how a literal's `const` is computed,
326
- * whether a `.check()`/`.meta()` constraint fragment exists, whether `.nullable()`
327
- * was applied — are delegated wholesale to the reader.
328
- */
359
+ * Structural reader over a validator-like node. The shared mapping algorithm
360
+ * ({@link jsonSchemaFromNode}) is parameterized by this interface so the same
361
+ * switch/recursion serves both inputs Lunora maps to JSON Schema: the runtime
362
+ * `@lunora/values` validator (children + metadata live on `_meta`), and the
363
+ * build-time validator IR consumed by codegen (children are plain fields, with
364
+ * no runtime metadata — so `constraints`/`isNullable` may be inert there).
365
+ *
366
+ * A reader normalizes a `TNode` to the small set of children/leaves the mapper
367
+ * recurses over. Composite accessors (`inner`/`shape`/`members`/`valueChild`)
368
+ * return the same `TNode` type so the mapper can recurse uniformly; leaf concerns
369
+ * that differ between the two sources — how a literal's `const` is computed,
370
+ * whether a `.check()`/`.meta()` constraint fragment exists, whether `.nullable()`
371
+ * was applied — are delegated wholesale to the reader.
372
+ */
329
373
  interface SchemaNodeReader<TNode> {
330
374
  /**
331
- * The `.check()`/`.meta()` JSON Schema fragment to shallow-merge onto the
332
- * node, or `undefined` when none (the IR side never carries one). Constraint
333
- * keys win over the base on conflict so a refinement can tighten — never
334
- * silently weaken — the schema.
335
- */
375
+ * The `.check()`/`.meta()` JSON Schema fragment to shallow-merge onto the
376
+ * node, or `undefined` when none (the IR side never carries one). Constraint
377
+ * keys win over the base on conflict so a refinement can tighten — never
378
+ * silently weaken — the schema.
379
+ */
336
380
  constraints: (node: TNode) => JsonSchema | undefined;
337
381
  /** Inner child of an `array`/`optional` node. May be absent on the IR side. */
338
382
  inner: (node: TNode) => TNode | undefined;
@@ -341,10 +385,10 @@ interface SchemaNodeReader<TNode> {
341
385
  /** Discriminating validator kind. */
342
386
  kind: (node: TNode) => ValidatorKind;
343
387
  /**
344
- * The JSON Schema `const` fragment for a `literal` node. Computed differently
345
- * per source — runtime reads the live `_meta.value`; the IR parses verbatim
346
- * source text — so the reader owns it entirely.
347
- */
388
+ * The JSON Schema `const` fragment for a `literal` node. Computed differently
389
+ * per source — runtime reads the live `_meta.value`; the IR parses verbatim
390
+ * source text — so the reader owns it entirely.
391
+ */
348
392
  literalSchema: (node: TNode) => JsonSchema;
349
393
  /** Member nodes of a `union`. */
350
394
  members: (node: TNode) => ReadonlyArray<TNode>;
@@ -356,62 +400,109 @@ interface SchemaNodeReader<TNode> {
356
400
  valueChild: (node: TNode) => TNode | undefined;
357
401
  }
358
402
  /**
359
- * The single validator→JSON-Schema mapping algorithm, shared by the runtime
360
- * `toJsonSchema` (over `@lunora/values` validators) and codegen's IR-backed
361
- * mapper. It walks a node recursively via the supplied {@link SchemaNodeReader},
362
- * so nested objects/arrays/unions/records are fully expanded (never collapsed to
363
- * one level).
364
- *
365
- * `date`/`timestamp` are epoch-millisecond numbers in Lunora (not ISO strings),
366
- * so they schema as integers; `bigint` schemas as an int64 (JSON has no bigint
367
- * type, so `format: int64` is the conventional OpenAPI carrier); `bytes` is an
368
- * `ArrayBuffer`, surfaced as base64 per JSON Schema 2020-12 content encoding.
369
- *
370
- * A `.check()`/`.meta()` JSON Schema fragment (when the reader exposes one) is
371
- * shallow-merged onto the node — constraint keys win on conflict. A `.nullable()`
372
- * node widens to also accept `null`; constraints describe the underlying value,
373
- * so they ride inside the non-null branch rather than on the wrapping `anyOf`.
374
- */
403
+ * The single validator→JSON-Schema mapping algorithm, shared by the runtime
404
+ * `toJsonSchema` (over `@lunora/values` validators) and codegen's IR-backed
405
+ * mapper. It walks a node recursively via the supplied {@link SchemaNodeReader},
406
+ * so nested objects/arrays/unions/records are fully expanded (never collapsed to
407
+ * one level).
408
+ *
409
+ * `date`/`timestamp` are epoch-millisecond numbers in Lunora (not ISO strings),
410
+ * so they schema as integers; `bigint` schemas as an int64 (JSON has no bigint
411
+ * type, so `format: int64` is the conventional OpenAPI carrier); `bytes` is an
412
+ * `ArrayBuffer`, surfaced as base64 per JSON Schema 2020-12 content encoding.
413
+ *
414
+ * A `.check()`/`.meta()` JSON Schema fragment (when the reader exposes one) is
415
+ * shallow-merged onto the node — constraint keys win on conflict. A `.nullable()`
416
+ * node widens to also accept `null`; constraints describe the underlying value,
417
+ * so they ride inside the non-null branch rather than on the wrapping `anyOf`.
418
+ */
375
419
  declare const jsonSchemaFromNode: <TNode>(node: TNode, reader: SchemaNodeReader<TNode>) => JsonSchema;
376
420
  /**
377
- * Build `{ type: "object", properties, required, additionalProperties: false }`
378
- * from a node shape. A `v.optional(...)` property is the only thing that drops
379
- * out of `required`; every other property is required.
380
- */
421
+ * Build `{ type: "object", properties, required, additionalProperties: false }`
422
+ * from a node shape. A `v.optional(...)` property is the only thing that drops
423
+ * out of `required`; every other property is required.
424
+ */
381
425
  declare const objectSchemaFromNodes: <TNode>(shape: Record<string, TNode>, reader: SchemaNodeReader<TNode>) => JsonSchema;
382
426
  /**
383
- * Convert a single `@lunora/values` validator to a JSON Schema node (Draft
384
- * 2020-12 / OpenAPI 3.1). A thin wrapper over the shared {@link jsonSchemaFromNode}
385
- * core with the runtime {@link validatorReader}; see that core for the full
386
- * kind→schema mapping (date/timestamp → epoch-ms integer, bigint → int64, bytes →
387
- * base64, id → annotated string, literal → `const`, optionality via the parent
388
- * `required` list, `.nullable()` widening, `.check()`/`.meta()` constraint merge).
389
- */
427
+ * Convert a single `@lunora/values` validator to a JSON Schema node (Draft
428
+ * 2020-12 / OpenAPI 3.1). A thin wrapper over the shared {@link jsonSchemaFromNode}
429
+ * core with the runtime {@link validatorReader}; see that core for the full
430
+ * kind→schema mapping (date/timestamp → epoch-ms integer, bigint → int64, bytes →
431
+ * base64, id → annotated string, literal → `const`, optionality via the parent
432
+ * `required` list, `.nullable()` widening, `.check()`/`.meta()` constraint merge).
433
+ */
390
434
  declare const toJsonSchema: (validator: Validator) => JsonSchema;
391
435
  /**
392
- * Convert a function's argument validators (a name-to-validator map) into a
393
- * single JSON Schema object. Non-`optional` arguments are `required`; the result
394
- * is the request `params`/`args` schema an OpenAPI operation or OpenRPC method
395
- * advertises. An empty arg map yields an empty (but valid) object schema.
396
- */
436
+ * Convert a function's argument validators (a name-to-validator map) into a
437
+ * single JSON Schema object. Non-`optional` arguments are `required`; the result
438
+ * is the request `params`/`args` schema an OpenAPI operation or OpenRPC method
439
+ * advertises. An empty arg map yields an empty (but valid) object schema.
440
+ */
397
441
  declare const argsToJsonSchema: (args: Record<string, Validator>) => JsonSchema;
398
442
  /** Map of validators describing a record of named fields (a function's args, a step's args, an HTTP query/body/params). */
399
443
  type ValidatorMap = Record<string, Validator>;
400
- /** Infer the object type from a {@link ValidatorMap} — optional validators (`v.optional`) become optional keys. */
401
- type InferValidatorMap<A extends ValidatorMap> = { [K in keyof A as undefined extends Infer<A[K]> ? K : never]?: Infer<A[K]> } & { [K in keyof A as undefined extends Infer<A[K]> ? never : K]: Infer<A[K]> };
402
- /**
403
- * Validate each declared field of `source` through its validator, re-wrapping
404
- * any {@link ValidationError} with a `label.&lt;key>:` prefix and the rebuilt path
405
- * `[key, ...error.path]` so the failure points at the offending field. Optional
406
- * fields absent from the source are skipped (so `v.optional` passes and a
407
- * required validator fails on `undefined`).
408
- *
409
- * The single arg-/field-parsing implementation shared across the framework — the
410
- * procedure builder (label `args`), the HTTP route builder (`searchParams` /
411
- * `body` / `params`), and `@lunora/workflow`'s reusable steps (`step args`) — so
412
- * the error-prefixing and optional-skip semantics can't drift apart. The `label`
413
- * is the only thing each caller varies.
414
- */
444
+ /**
445
+ * Infer the object type from a {@link ValidatorMap} optional validators
446
+ * (`v.optional`) become optional keys. Shares the single optionality rule with
447
+ * `ObjectShapeType` via {@link OptionalizeShape}, so args-map and object-shape
448
+ * inference can never drift.
449
+ */
450
+ type InferValidatorMap<A extends ValidatorMap> = OptionalizeShape<{ [K in keyof A]: Infer<A[K]>; }>;
451
+ /**
452
+ * A precompiled fast-path parser for one {@link ValidatorMap}. Returns the fully
453
+ * built, validated record on a confident success, or the {@link DEFER_VALIDATION}
454
+ * sentinel to hand the input back to the interpreted parser.
455
+ *
456
+ * The contract is soundness, not completeness: a compiled parser may return
457
+ * {@link DEFER_VALIDATION} for any input it is not certain about (the interpreted
458
+ * path then runs and either succeeds or throws the canonical error), but it must
459
+ * NEVER return a built record for input the interpreted parser would reject, and
460
+ * the record it returns must be byte-for-byte what the interpreted parser would
461
+ * have produced. This lets `@lunora/codegen` emit zero-allocation structural
462
+ * checks (the common case) while every error message and every tricky validator
463
+ * still flows through the single interpreted implementation below — so error
464
+ * contracts can never drift.
465
+ *
466
+ * The `source` parameter is intentionally `any`: the codegen-emitted body is
467
+ * plain JavaScript (no type annotations — it must also be loadable via
468
+ * `new Function` in the compiler's differential tests) that index-walks the input
469
+ * to arbitrary depth, which strict TypeScript forbids on `unknown`/`object`. An
470
+ * `any` input lets the emitted structural checks type-check cleanly while the
471
+ * RESULT stays strongly typed; soundness is enforced by the differential test
472
+ * harness, not the input type.
473
+ */
474
+ type CompiledValidatorMap = (source: any) => Record<string, unknown> | typeof DEFER_VALIDATION;
475
+ /**
476
+ * Sentinel a {@link CompiledValidatorMap} returns to defer to the interpreted
477
+ * parser. A unique symbol (never a valid parse result — {@link parseValidatorMap}
478
+ * always yields a record) so the seam can distinguish "compiled handled it" from
479
+ * "compiled bailed" with a single identity check and no per-call allocation.
480
+ */
481
+ declare const DEFER_VALIDATION: unique symbol;
482
+ /**
483
+ * Install a compiled fast-path parser for `validators`. Idempotent-ish: a second
484
+ * install overwrites the first (codegen emits each map once, so this only matters
485
+ * if a host installs by hand). See {@link CompiledValidatorMap} for the contract
486
+ * the parser must honour.
487
+ */
488
+ declare const installCompiledValidatorMap: (validators: object, compiled: CompiledValidatorMap) => void;
489
+ /**
490
+ * Validate each declared field of `source` through its validator, re-wrapping
491
+ * any {@link ValidationError} with a `label.&lt;key>:` prefix and the rebuilt path
492
+ * `[key, ...error.path]` so the failure points at the offending field. Optional
493
+ * fields absent from the source are skipped (so `v.optional` passes and a
494
+ * required validator fails on `undefined`).
495
+ *
496
+ * The single arg-/field-parsing implementation shared across the framework — the
497
+ * procedure builder (label `args`), the HTTP route builder (`searchParams` /
498
+ * `body` / `params`), and `@lunora/workflow`'s reusable steps (`step args`) — so
499
+ * the error-prefixing and optional-skip semantics can't drift apart. The `label`
500
+ * is the only thing each caller varies.
501
+ *
502
+ * When a codegen-emitted {@link CompiledValidatorMap} is installed for this exact
503
+ * `validators` object, the fast path runs first; it either returns the finished
504
+ * record (a confident success — the common case) or {@link DEFER_VALIDATION}, in
505
+ * which case the interpreted loop below runs and owns the result (and any error).
506
+ */
415
507
  declare const parseValidatorMap: (validators: ValidatorMap, source: Record<string, unknown>, label: string) => Record<string, unknown>;
416
- declare const VERSION = "0.0.0";
417
- export { type CheckOptions, type Column, type ColumnMeta, type ColumnValidator, type Id, type Infer, type InferInsert, type InferSelect, type InferStandardOutput, type InferValidatorMap, type InsertShape, type JsonSchema, type JsonSchemaFragment, type MetaOptions, type SchemaNodeReader, type SelectShape, type ServerDefaultContext, type TimestampColumnValidator, VERSION, ValidationError, type ValidationPath, type Validator, type ValidatorKind, type ValidatorMap, argsToJsonSchema, describeValue, formatPath, isOrWrapsFromValidator, jsonSchemaFromNode, objectSchemaFromNodes, optionalInner, parseValidatorMap, toJsonSchema, v };
508
+ export { type CheckOptions, type Column, type ColumnMeta, type ColumnValidator, type CompiledValidatorMap, DEFER_VALIDATION, type GeoPoint, type Id, type Infer, type InferInsert, type InferSelect, type InferStandardOutput, type InferValidatorMap, type InsertShape, type JsonSchema, type JsonSchemaFragment, type MetaOptions, type SchemaNodeReader, type SelectShape, type ServerDefaultContext, type TimestampColumnValidator, ValidationError, type ValidationPath, type Validator, type ValidatorKind, type ValidatorMap, argsToJsonSchema, describeValue, formatPath, installCompiledValidatorMap, isOrWrapsFromValidator, jsonSchemaFromNode, objectSchemaFromNodes, optionalInner, parseValidatorMap, toJsonSchema, v };