@mindstudio-ai/agent 0.1.176 → 0.1.178

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 (50) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/analytics/index.d.ts +384 -0
  3. package/dist/auth/index.d.ts +113 -0
  4. package/dist/browser/index.d.ts +332 -0
  5. package/dist/cli.js +29 -29
  6. package/dist/client.d.ts +767 -0
  7. package/dist/config.d.ts +13 -0
  8. package/dist/context.d.ts +125 -0
  9. package/dist/datasources/index.d.ts +52 -0
  10. package/dist/datasources/source.d.ts +1074 -0
  11. package/dist/db/aggregate.d.ts +101 -0
  12. package/dist/db/index.d.ts +280 -0
  13. package/dist/db/mutation.d.ts +65 -0
  14. package/dist/db/predicate.d.ts +85 -0
  15. package/dist/db/query.d.ts +233 -0
  16. package/dist/db/raw.d.ts +36 -0
  17. package/dist/db/readBatching.d.ts +36 -0
  18. package/dist/db/scanHints.d.ts +8 -0
  19. package/dist/db/sql.d.ts +136 -0
  20. package/dist/db/table.d.ts +146 -0
  21. package/dist/db/time.d.ts +17 -0
  22. package/dist/db/types.d.ts +237 -0
  23. package/dist/db-ws.d.ts +35 -0
  24. package/dist/email/index.d.ts +396 -0
  25. package/dist/errors.d.ts +34 -0
  26. package/dist/events/index.d.ts +127 -0
  27. package/dist/files/index.d.ts +62 -0
  28. package/dist/files/store.d.ts +244 -0
  29. package/dist/generated/metadata.d.ts +8 -0
  30. package/dist/generated/snippets.d.ts +8 -0
  31. package/dist/generated/steps.d.ts +2745 -0
  32. package/dist/generated/types.d.ts +4234 -0
  33. package/dist/http.d.ts +22 -0
  34. package/dist/index.d.ts +59 -13329
  35. package/dist/index.js +17 -17
  36. package/dist/index.js.map +7 -1
  37. package/dist/jewel/index.d.ts +325 -0
  38. package/dist/mapper/index.d.ts +229 -0
  39. package/dist/rate-limit.d.ts +25 -0
  40. package/dist/reader/index.d.ts +170 -0
  41. package/dist/respond.d.ts +68 -0
  42. package/dist/task/index.d.ts +18 -0
  43. package/dist/task/local.d.ts +48 -0
  44. package/dist/task/schema.d.ts +120 -0
  45. package/dist/task/types.d.ts +203 -0
  46. package/dist/types.d.ts +591 -0
  47. package/dist/voice/index.d.ts +87 -0
  48. package/llms.txt +2 -2
  49. package/package.json +6 -12
  50. package/dist/postinstall.js +0 -12115
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Aggregation spec types + shared logic for `Query.aggregate()` and the
3
+ * scalar aggregate terminals (sum/avg/countDistinct).
4
+ *
5
+ * The spec uses STRING column names (not accessors): `by: ['questionId']`,
6
+ * `{ sum: 'score' }`. Plain-object terms give reliable contextual typing of
7
+ * the result (`Pick<T, By[number]> & AggregateRow<T, S>`), follow the
8
+ * `upsert(conflictKey, ...)` string-key precedent, and can't hit the
9
+ * accessor-extraction failure mode — an invalid identifier is a hard error
10
+ * here, not a silent fetch-everything fallback.
11
+ *
12
+ * Empty-set semantics (the SQL path and the JS fallback in
13
+ * `computeAggregateInJs` MUST stay in lockstep — see the README's
14
+ * Aggregation section):
15
+ * count → 0; sum → 0 (SQL TOTAL(), never NULL); avg → null;
16
+ * countDistinct → 0; min/max → null. All aggregates skip NULL values.
17
+ */
18
+ import type { AppDatabaseColumnSchema } from '../types.js';
19
+ import { type AggregateFn } from './sql.js';
20
+ /** Column keys whose value type is number (nullable allowed). */
21
+ type NumericKey<T> = {
22
+ [K in keyof T & string]: NonNullable<T[K]> extends number ? K : never;
23
+ }[keyof T & string];
24
+ /** Column keys orderable by MIN/MAX — numbers and strings. */
25
+ type ComparableKey<T> = {
26
+ [K in keyof T & string]: NonNullable<T[K]> extends number | string ? K : never;
27
+ }[keyof T & string];
28
+ /**
29
+ * One aggregate in an `aggregate()` select spec. Exactly one function key
30
+ * per term:
31
+ * { count: true } · { sum: 'col' } · { avg: 'col' } ·
32
+ * { min: 'col' } · { max: 'col' } · { countDistinct: 'col' }
33
+ */
34
+ export type AggregateTerm<T> = {
35
+ count: true;
36
+ } | {
37
+ sum: NumericKey<T>;
38
+ } | {
39
+ avg: NumericKey<T>;
40
+ } | {
41
+ min: ComparableKey<T>;
42
+ } | {
43
+ max: ComparableKey<T>;
44
+ } | {
45
+ countDistinct: keyof T & string;
46
+ };
47
+ /** The `select` map: result property name → aggregate term. */
48
+ export type AggregateSelect<T> = Record<string, AggregateTerm<T>>;
49
+ /** Result value types per term (matching the empty-set semantics above). */
50
+ export type AggregateRow<T, S extends AggregateSelect<T>> = {
51
+ [K in keyof S]: S[K] extends {
52
+ count: true;
53
+ } ? number : S[K] extends {
54
+ sum: string;
55
+ } ? number : S[K] extends {
56
+ avg: string;
57
+ } ? number | null : S[K] extends {
58
+ countDistinct: string;
59
+ } ? number : S[K] extends {
60
+ min: infer C;
61
+ } ? C extends keyof T ? T[C] | null : never : S[K] extends {
62
+ max: infer C;
63
+ } ? C extends keyof T ? T[C] | null : never : never;
64
+ };
65
+ export interface NormalizedAggregateTerm {
66
+ alias: string;
67
+ fn: AggregateFn;
68
+ column?: string;
69
+ }
70
+ export interface NormalizedAggregateSpec {
71
+ by: string[];
72
+ select: NormalizedAggregateTerm[];
73
+ orderBy?: string;
74
+ desc?: boolean;
75
+ limit?: number;
76
+ }
77
+ /**
78
+ * Validate + normalize an aggregate() spec. Throws MindStudioError (400)
79
+ * on any malformed input so the agent loop self-corrects immediately,
80
+ * instead of shipping broken SQL or silently mis-grouping in JS.
81
+ */
82
+ export declare function normalizeAggregateSpec(spec: {
83
+ by?: readonly string[];
84
+ select: Record<string, Record<string, unknown>>;
85
+ orderBy?: string;
86
+ desc?: boolean;
87
+ limit?: number;
88
+ }): NormalizedAggregateSpec;
89
+ export declare function computeAggregateInJs(rows: Record<string, unknown>[], spec: NormalizedAggregateSpec): Record<string, unknown> | Record<string, unknown>[];
90
+ /**
91
+ * Deserialize grouped-aggregate result rows to match what the JS fallback
92
+ * produces from already-deserialized rows: group-key columns go through the
93
+ * normal column deserialization (@@user@@ strip, boolean 0/1, json), and a
94
+ * min/max alias adopts its SOURCE column's schema (so e.g. MAX of a user
95
+ * column loses its prefix). Other aggregate values (counts, sums, averages)
96
+ * are raw numbers and are deliberately NOT matched against the table schema —
97
+ * an alias that happens to share a name with, say, a boolean column must not
98
+ * get 0/1-converted.
99
+ */
100
+ export declare function deserializeAggregateRows(rows: unknown[], spec: NormalizedAggregateSpec, columns: AppDatabaseColumnSchema[]): Record<string, unknown>[];
101
+ export {};
@@ -0,0 +1,280 @@
1
+ /**
2
+ * The `db` namespace — factory and time helpers for MindStudio managed databases.
3
+ *
4
+ * This module provides `createDb()`, which builds the `Db` object that users
5
+ * interact with. The Db object has:
6
+ *
7
+ * - `defineTable<T>(name)` — creates a typed Table<T> for a given table name
8
+ * - Time helpers: `now()`, `days()`, `hours()`, `minutes()`, `ago()`, `fromNow()`
9
+ *
10
+ * ## How defineTable works
11
+ *
12
+ * `defineTable` is a factory that binds a table name to the correct database
13
+ * and execution context. It:
14
+ *
15
+ * 1. Looks up the table name in the app context database metadata
16
+ * 2. Resolves the databaseId (implicit if only one database exists)
17
+ * 3. Gets the column schema (for user-type handling and JSON parsing)
18
+ * 4. Returns a Table<T> instance bound to the executeQuery function
19
+ *
20
+ * Tables are typically defined at module scope and imported into route handlers:
21
+ *
22
+ * ```ts
23
+ * // tables/orders.ts
24
+ * import { db } from '@mindstudio-ai/agent';
25
+ * export const Orders = db.defineTable<Order>('orders');
26
+ *
27
+ * // routes/getOrders.ts
28
+ * import { Orders } from '../tables/orders';
29
+ * const active = await Orders.filter(o => o.status === 'active').take(10);
30
+ * ```
31
+ *
32
+ * Since `defineTable()` is lazy (no queries execute until you await something
33
+ * on the Table), it's safe to call at module scope. The actual database
34
+ * context resolution happens on first query execution.
35
+ *
36
+ * ## Time helpers
37
+ *
38
+ * All timestamps in MindStudio databases are unix timestamps (milliseconds
39
+ * since epoch). The time helpers make it easy to work with relative times
40
+ * without writing `Date.now() - 48 * 60 * 60 * 1000` everywhere:
41
+ *
42
+ * ```ts
43
+ * const cutoff = db.ago(db.days(2)); // 2 days ago (unix ms)
44
+ * const deadline = db.fromNow(db.hours(48)); // 48 hours from now
45
+ * const window = db.days(7) + db.hours(12); // composable durations
46
+ * ```
47
+ */
48
+ import type { AppDatabase, AuthTableConfig, User } from '../types.js';
49
+ import { Table } from './table.js';
50
+ import { Query } from './query.js';
51
+ import { Mutation } from './mutation.js';
52
+ import { RawQuery } from './raw.js';
53
+ import type { SqlQuery, SqlResult, SystemColumns, SystemFields } from './types.js';
54
+ /**
55
+ * Options for `db.defineTable()`.
56
+ */
57
+ export interface DefineTableOptions<T = unknown> {
58
+ /**
59
+ * Database name or ID to target. Required when the app has multiple
60
+ * databases and the table name alone is ambiguous.
61
+ *
62
+ * Accepts either the database's display name or its ID. The SDK
63
+ * matches against both.
64
+ *
65
+ * If omitted, the SDK resolves the database automatically:
66
+ * - Single database → used implicitly
67
+ * - Multiple databases → searched by table name
68
+ */
69
+ database?: string;
70
+ /**
71
+ * Unique constraints for the table. Each entry is an array of column
72
+ * names that together must be unique. The SDK communicates these to
73
+ * the platform which creates the corresponding SQLite UNIQUE indexes.
74
+ *
75
+ * Required for `upsert()` — the conflict key must match a declared
76
+ * unique constraint.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * // Single column unique
81
+ * db.defineTable<User>('users', { unique: [['email']] });
82
+ *
83
+ * // Compound unique
84
+ * db.defineTable<Membership>('memberships', { unique: [['userId', 'orgId']] });
85
+ *
86
+ * // Multiple constraints
87
+ * db.defineTable<User>('users', { unique: [['email'], ['slug']] });
88
+ * ```
89
+ */
90
+ unique?: (keyof T & string)[][];
91
+ /**
92
+ * Indexes for the table, for the columns its queries filter or sort by.
93
+ * Each entry is an array of column names, most selective first; the
94
+ * platform creates a plain (non-unique) SQLite index for each, and adds or
95
+ * drops one in place when the list changes, without rebuilding the table.
96
+ * An index makes a lookup on its columns read a few rows rather than the
97
+ * whole table, and costs a little on every write, so declare the ones the
98
+ * app's queries use.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * db.defineTable<Order>('orders', {
103
+ * indexes: [['status'], ['customerId', 'createdAt']],
104
+ * });
105
+ * ```
106
+ */
107
+ indexes?: (keyof T & string)[][];
108
+ /**
109
+ * Default values for columns, applied client-side in `push()` and
110
+ * `upsert()`. Explicit values in the input override defaults.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * db.defineTable<Order>('orders', {
115
+ * defaults: { status: 'pending', retryCount: 0 },
116
+ * });
117
+ * ```
118
+ */
119
+ defaults?: Partial<Omit<T, SystemFields>>;
120
+ }
121
+ export { Table } from './table.js';
122
+ export { Query } from './query.js';
123
+ export { Mutation } from './mutation.js';
124
+ export { RawQuery } from './raw.js';
125
+ export type { CompiledRawQuery } from './raw.js';
126
+ export type { AggregateSelect, AggregateTerm, AggregateRow, } from './aggregate.js';
127
+ export type { Predicate, Accessor, PushInput, UpdateInput, Row, SettableSystemColumns, SystemColumns, SystemFields, TableConfig, } from './types.js';
128
+ /**
129
+ * The `db` namespace object. Contains `defineTable()` for creating typed
130
+ * collections and time helpers for working with unix timestamps.
131
+ */
132
+ export interface Db {
133
+ /**
134
+ * Define a typed table. Returns a Table<T> bound to the app's managed
135
+ * database. The table name must match a table in the app's database schema.
136
+ *
137
+ * Tables are lazy — nothing executes until you call a method on the Table
138
+ * and await the result. This makes it safe to call `defineTable()` at
139
+ * module scope.
140
+ *
141
+ * Database resolution:
142
+ * - If the app has a single database (common case), it's used automatically.
143
+ * - If the app has multiple databases, pass `{ database }` with the
144
+ * database name or ID to target the right one. If omitted, the SDK
145
+ * searches all databases by table name.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * // Single database (common) — no need to specify
150
+ * const Orders = db.defineTable<Order>('orders');
151
+ *
152
+ * // Multiple databases — specify which one
153
+ * const Orders = db.defineTable<Order>('orders', { database: 'main' });
154
+ * ```
155
+ */
156
+ defineTable<T>(name: string, options?: DefineTableOptions<T>): Table<T & SystemColumns>;
157
+ /** Returns the current time as a unix timestamp (ms). Equivalent to `Date.now()`. */
158
+ now(): number;
159
+ /** Returns milliseconds for n days. Composable with `+`. */
160
+ days(n: number): number;
161
+ /** Returns milliseconds for n hours. Composable with `+`. */
162
+ hours(n: number): number;
163
+ /** Returns milliseconds for n minutes. Composable with `+`. */
164
+ minutes(n: number): number;
165
+ /** Returns a unix timestamp for (now - duration). Use with days/hours/minutes. */
166
+ ago(ms: number): number;
167
+ /** Returns a unix timestamp for (now + duration). Use with days/hours/minutes. */
168
+ fromNow(ms: number): number;
169
+ /**
170
+ * Type a plain UUID string as a `User` reference, for writing into
171
+ * user-typed columns without an `as any` cast. Strips any existing
172
+ * `@@user@@` prefix so the input is always a bare UUID in app code.
173
+ *
174
+ * The SDK adds the `@@user@@` prefix automatically on write — you do
175
+ * not need to (and should not) add it yourself.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * await Orders.push({
180
+ * requestedBy: db.userRef(someUuid),
181
+ * ...
182
+ * });
183
+ * ```
184
+ */
185
+ userRef(id: string): User;
186
+ /**
187
+ * Run a raw read-only SQL statement against the app's managed database —
188
+ * the escape hatch for joins, subqueries, and anything the typed Table
189
+ * API can't express. SELECT/WITH only; writes are rejected — use Table
190
+ * methods (push/update/upsert/remove) for writes.
191
+ *
192
+ * Positional `?` bind params. Lazy and batchable: await it directly, or
193
+ * pass it to `db.batch()` alongside Query/Mutation objects.
194
+ *
195
+ * Multi-database apps: pass `{ database }` (name or ID); single-database
196
+ * apps resolve automatically.
197
+ *
198
+ * Note: raw rows come back close to how SQLite stores them and may not
199
+ * exactly match the typed table API's representations.
200
+ *
201
+ * @example
202
+ * ```ts
203
+ * const rows = await db.sql<{ questionId: string; n: number }>(
204
+ * 'SELECT questionId, COUNT(*) AS n FROM answers WHERE surveyId = ? GROUP BY questionId',
205
+ * [surveyId],
206
+ * );
207
+ * ```
208
+ */
209
+ sql<T = Record<string, unknown>>(query: string, params?: unknown[], options?: {
210
+ database?: string;
211
+ }): RawQuery<T[]>;
212
+ /**
213
+ * Execute multiple reads and writes in a single round trip. All
214
+ * operations run on the same database connection, eliminating
215
+ * per-operation HTTP overhead. Writes execute in argument order.
216
+ *
217
+ * Accepts Query objects (reads) and Mutation objects (writes from
218
+ * push, update, remove, removeAll, clear). Compiles them to SQL,
219
+ * sends all in one batch request, and returns typed results.
220
+ *
221
+ * Only un-awaited Query/Mutation objects can be batched — their SQL is
222
+ * compiled and bundled. A plain Promise has no SQL to extract, so it is
223
+ * rejected at the type level (and would throw at runtime): pass
224
+ * `Table.filter(...)`, not `await`ed results or wrapper functions.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * // Mixed reads and writes in one round trip
229
+ * const [, newCard, cards] = await db.batch(
230
+ * Cards.update(card1.id, { position: 1 }),
231
+ * Cards.push({ title: 'New', columnId, position: 0 }),
232
+ * Cards.filter(c => c.columnId === columnId),
233
+ * );
234
+ * ```
235
+ */
236
+ batch<A>(q1: Batchable<A>): Promise<[A]>;
237
+ batch<A, B>(q1: Batchable<A>, q2: Batchable<B>): Promise<[A, B]>;
238
+ batch<A, B, C>(q1: Batchable<A>, q2: Batchable<B>, q3: Batchable<C>): Promise<[A, B, C]>;
239
+ batch<A, B, C, D>(q1: Batchable<A>, q2: Batchable<B>, q3: Batchable<C>, q4: Batchable<D>): Promise<[A, B, C, D]>;
240
+ batch<A, B, C, D, E>(q1: Batchable<A>, q2: Batchable<B>, q3: Batchable<C>, q4: Batchable<D>, q5: Batchable<E>): Promise<[A, B, C, D, E]>;
241
+ batch(...queries: Batchable<unknown>[]): Promise<unknown[]>;
242
+ }
243
+ /**
244
+ * An operation `db.batch()` can bundle: an un-awaited Query (read),
245
+ * Mutation (write), or RawQuery (db.sql). The batch executor compiles
246
+ * these to SQL — a plain Promise carries no SQL and cannot be batched,
247
+ * which is why this is not `PromiseLike`.
248
+ */
249
+ export type Batchable<A> = Query<any, A> | Mutation<A> | RawQuery<A>;
250
+ /**
251
+ * Create a Db namespace object from app context database metadata.
252
+ *
253
+ * @param databases - Database metadata from `getAppContext()` or sandbox globals
254
+ * @param executeBatch - Bound function that executes SQL batches via POST /_internal/v2/db/query
255
+ * @returns The Db object with defineTable() and time helpers
256
+ *
257
+ * @internal Called by MindStudioAgent during context hydration. Not part of
258
+ * the public API — users access `db` via the agent instance or top-level export.
259
+ */
260
+ export declare function createDb(databases: AppDatabase[], executeBatch: (databaseId: string, queries: SqlQuery[]) => Promise<SqlResult[]>, authConfig?: AuthTableConfig, syncRoles?: (userId: string, roles: unknown) => Promise<void>): Db;
261
+ /**
262
+ * Validate a `db.sql()` statement: non-empty, and read-only. The gate is
263
+ * advisory — it catches accidents, not adversaries (method authors already
264
+ * control the SQL strings the typed API compiles, so the trust model is
265
+ * unchanged). Writes belong on Table methods, which enforce managed-column
266
+ * rules and role sync.
267
+ *
268
+ * @internal Shared by createDb() and the client's lazy Db proxy.
269
+ */
270
+ export declare function validateRawSql(query: string): void;
271
+ /**
272
+ * Resolve a database from app context metadata — by name or ID when a hint
273
+ * is given, implicitly when the app has exactly one database. Used by
274
+ * `db.sql()` directly and by `resolveTable`'s hint branch; unlike table
275
+ * resolution there is no table name to disambiguate with, so multiple
276
+ * databases without a hint is an error.
277
+ *
278
+ * @internal Also used by the client's lazy Db proxy at execution time.
279
+ */
280
+ export declare function resolveDatabase(databases: AppDatabase[], hint?: string): AppDatabase;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Mutation<T> — a lazy write operation backed by SQLite.
3
+ *
4
+ * Created by Table write methods (push, update, remove, removeAll, clear).
5
+ * Like Query, implements PromiseLike so `await` triggers execution. Unlike
6
+ * Query, there's no chaining — a Mutation is a fixed set of SQL statements
7
+ * with a result processor.
8
+ *
9
+ * ## Batch support
10
+ *
11
+ * `db.batch()` calls `_compile()` to extract the SQL without executing,
12
+ * then bundles it with other operations into a single round trip. After
13
+ * execution, `_processResults()` deserializes the raw SQL results.
14
+ *
15
+ * ## SQL is built when it runs
16
+ *
17
+ * A Mutation holds a builder rather than its statements, called when it's
18
+ * compiled or executed. The statements depend on the table's columns (a user
19
+ * column's `@@user@@` prefix) and managed columns, which a lazy table only
20
+ * knows once the app's context is loaded (`TableConfig.ready`), and that can
21
+ * be after the write method was called.
22
+ *
23
+ * ## Non-batchable mutations
24
+ *
25
+ * Some mutations (e.g. `removeAll` with a JS-fallback predicate) require
26
+ * multi-step execution that can't be expressed as a fixed SQL batch. A
27
+ * builder says so by returning null, and the mutation runs its `fallback`
28
+ * instead: fine when awaited standalone, but it throws if passed to
29
+ * `db.batch()`. Whether it can be expressed may depend on the table's
30
+ * columns, so it's decided when the SQL is built, not when the write method
31
+ * was called.
32
+ */
33
+ import type { TableConfig, SqlQuery, SqlResult } from './types.js';
34
+ export interface CompiledMutation<TResult> {
35
+ type: 'mutation';
36
+ queries: SqlQuery[];
37
+ config: TableConfig;
38
+ processResult: (results: SqlResult[]) => TResult;
39
+ }
40
+ export declare class Mutation<TResult> implements PromiseLike<TResult> {
41
+ /** @internal */
42
+ private readonly _config;
43
+ /** @internal The statements, or null when the write can't be one batch. */
44
+ private readonly _build;
45
+ /** @internal */
46
+ private readonly _processResult;
47
+ /** @internal What runs when `_build` returns null (e.g. removeAll's JS fallback). */
48
+ private readonly _fallback;
49
+ constructor(config: TableConfig, build: () => SqlQuery[] | null, processResult: (results: SqlResult[]) => TResult, fallback?: () => Promise<TResult>);
50
+ then<T1 = TResult, T2 = never>(onfulfilled?: ((value: TResult) => T1 | PromiseLike<T1>) | null, onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<T1 | T2>;
51
+ catch<T2 = never>(onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<TResult | T2>;
52
+ /**
53
+ * @internal Compile this mutation into SQL for batch execution.
54
+ * Returns the queries and a result processor.
55
+ *
56
+ * Throws if it can't be expressed as SQL (its builder returned null).
57
+ */
58
+ _compile(): CompiledMutation<TResult>;
59
+ /**
60
+ * @internal Process raw SQL results into the typed result.
61
+ * Used by db.batch() after executing the compiled queries.
62
+ */
63
+ static _processResults<T>(results: SqlResult[], compiled: CompiledMutation<T>): T;
64
+ private _execute;
65
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Predicate compiler — converts JS arrow functions to SQL WHERE clauses.
3
+ *
4
+ * This is the core complexity of the `db` namespace. When users write:
5
+ *
6
+ * ```ts
7
+ * orders.filter(o => o.status === 'active' && o.amount > 5000)
8
+ * ```
9
+ *
10
+ * ...the compiler parses the function's source code and produces:
11
+ *
12
+ * ```sql
13
+ * WHERE (status = ? AND amount > ?) -- params: ['active', 5000]
14
+ * ```
15
+ *
16
+ * ## The promise
17
+ *
18
+ * A compiled predicate selects exactly the rows the function would. Where the
19
+ * compiler can't say that for sure, it doesn't compile, and the caller runs the
20
+ * function over every row instead. Two things make "exactly" harder than it
21
+ * looks:
22
+ *
23
+ * - **NULL.** SQL's comparisons with NULL are unknown, JS's with `null` are
24
+ * true or false (`null < 5` is true, `null !== 'a'` is true). Each leaf adds
25
+ * `OR col IS NULL` exactly when JS's answer for a null column is true, worked
26
+ * out at compile time, and `!` is pushed down to the leaves (De Morgan), so
27
+ * no `NOT` ever meets an unknown.
28
+ * - **The source isn't the author's.** A method's code is bundled by esbuild,
29
+ * so `fn.toString()` is esbuild's printing of it: `5000` is `5e3`, `'Zürich'`
30
+ * is `"Z\xFCrich"`, `undefined` is `void 0`, and a string holding both quote
31
+ * kinds is a template literal. The tokenizer reads all of those as JS would.
32
+ *
33
+ * ## How it works
34
+ *
35
+ * 1. **Extract source**: `fn.toString()`, then the parameter names and body
36
+ * 2. **Tokenize**: identifiers, strings, numbers, operators, punctuation
37
+ * 3. **Parse**: a recursive descent parser builds a small AST. A value on the
38
+ * right of a comparison may be a constant expression, evaluated here:
39
+ * arithmetic, `Date.now()`, the `db` time helpers (`db.ago(db.days(7))`) and
40
+ * `$` bindings
41
+ * 4. **Compile**: walk the AST and emit SQL, with every value a bound param
42
+ *
43
+ * ## Supported patterns
44
+ *
45
+ * - Comparisons: `o.field === value`, `!==`, `==`, `!=`, `<`, `>`, `<=`, `>=`,
46
+ * either way round (`5 < o.n`)
47
+ * - Null checks: `o.field === null`, `o.field != null`
48
+ * - `&&`, `||`, `!expr`, and truthiness: `o.active`, `!o.deleted`
49
+ * - `['a','b'].includes(o.field)` and `$.ids.includes(o.field)` → membership
50
+ * - `o.field.includes('text')`: a substring on a text column (case-sensitive,
51
+ * as JS's is), membership on a json column
52
+ * - Bindings: `(o, $) => o.field === $.value` with a bindings argument. The
53
+ * second parameter holds outer-scope values the SDK resolves at compile
54
+ * time; a closure variable can't be read from outside the function, so a
55
+ * predicate that uses one runs in JS.
56
+ *
57
+ * ## Fallback strategy
58
+ *
59
+ * If the compiler meets anything it doesn't recognize, it returns a `js`
60
+ * result instead, and the caller fetches the rows and runs the original
61
+ * function. filter() always works; the SQL path is an optimization. A warning
62
+ * is logged on fallback so developers know they're on the slow path.
63
+ */
64
+ import type { AppDatabaseColumnSchema } from '../types.js';
65
+ import type { CompiledPredicate, Predicate, PredicateBindings } from './types.js';
66
+ /**
67
+ * Attempt to compile a predicate function to a SQL WHERE clause.
68
+ *
69
+ * @param fn - The predicate function (e.g. `o => o.status === 'active'`)
70
+ * @param columns - The table's column schema: its types decide how
71
+ * truthiness and `.includes()` compile, and a value compared with a user
72
+ * column is written as it's stored, `@@user@@<id>`, since app code compares
73
+ * bare IDs.
74
+ * @returns `{ type: 'sql', where, params }`, or `{ type: 'js', fn, reason }`
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * compilePredicate(o => o.status === 'active');
79
+ * // { type: 'sql', where: 'status = ?', params: ['active'] }
80
+ *
81
+ * compilePredicate(o => o.name.startsWith('A'));
82
+ * // { type: 'js', fn: [original function], reason: '...' }
83
+ * ```
84
+ */
85
+ export declare function compilePredicate<T>(fn: Predicate<T>, bindings?: PredicateBindings, columns?: AppDatabaseColumnSchema[]): CompiledPredicate<T>;