@mindstudio-ai/agent 0.1.176 → 0.1.177
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/CHANGELOG.md +7 -0
- package/dist/analytics/index.d.ts +384 -0
- package/dist/auth/index.d.ts +113 -0
- package/dist/browser/index.d.ts +332 -0
- package/dist/cli.js +27 -27
- package/dist/client.d.ts +767 -0
- package/dist/config.d.ts +13 -0
- package/dist/context.d.ts +125 -0
- package/dist/datasources/index.d.ts +52 -0
- package/dist/datasources/source.d.ts +1074 -0
- package/dist/db/aggregate.d.ts +101 -0
- package/dist/db/index.d.ts +280 -0
- package/dist/db/mutation.d.ts +65 -0
- package/dist/db/predicate.d.ts +85 -0
- package/dist/db/query.d.ts +233 -0
- package/dist/db/raw.d.ts +36 -0
- package/dist/db/readBatching.d.ts +36 -0
- package/dist/db/scanHints.d.ts +8 -0
- package/dist/db/sql.d.ts +136 -0
- package/dist/db/table.d.ts +146 -0
- package/dist/db/time.d.ts +17 -0
- package/dist/db/types.d.ts +237 -0
- package/dist/db-ws.d.ts +35 -0
- package/dist/email/index.d.ts +396 -0
- package/dist/errors.d.ts +34 -0
- package/dist/events/index.d.ts +127 -0
- package/dist/files/index.d.ts +62 -0
- package/dist/files/store.d.ts +244 -0
- package/dist/generated/metadata.d.ts +8 -0
- package/dist/generated/snippets.d.ts +8 -0
- package/dist/generated/steps.d.ts +2745 -0
- package/dist/generated/types.d.ts +4234 -0
- package/dist/http.d.ts +22 -0
- package/dist/index.d.ts +59 -13329
- package/dist/index.js +15 -15
- package/dist/index.js.map +7 -1
- package/dist/jewel/index.d.ts +325 -0
- package/dist/mapper/index.d.ts +229 -0
- package/dist/rate-limit.d.ts +25 -0
- package/dist/reader/index.d.ts +170 -0
- package/dist/respond.d.ts +68 -0
- package/dist/task/index.d.ts +18 -0
- package/dist/task/local.d.ts +48 -0
- package/dist/task/schema.d.ts +120 -0
- package/dist/task/types.d.ts +203 -0
- package/dist/types.d.ts +591 -0
- package/dist/voice/index.d.ts +87 -0
- package/package.json +6 -12
- package/dist/postinstall.js +0 -12115
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Query chain builder — lazy, immutable query construction for database reads.
|
|
3
|
+
*
|
|
4
|
+
* A Query<T> represents a pending database query. It accumulates operations
|
|
5
|
+
* (filter, sort, limit, skip) without executing anything. Execution happens
|
|
6
|
+
* only when the query is awaited (via PromiseLike) or a terminal method
|
|
7
|
+
* is called (first, last, count, some, every, min, max, groupBy).
|
|
8
|
+
*
|
|
9
|
+
* ## Immutability
|
|
10
|
+
*
|
|
11
|
+
* Every chain method returns a NEW Query instance. This means chains can
|
|
12
|
+
* safely fork:
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* const base = Orders.filter(o => o.status === 'active');
|
|
16
|
+
* const recent = base.sortBy(o => o.createdAt).reverse().take(10);
|
|
17
|
+
* const count = await base.count(); // doesn't affect `recent`
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* ## Execution strategy (SQL fast path vs JS fallback)
|
|
21
|
+
*
|
|
22
|
+
* When a Query is executed, it compiles as much of the chain to SQL as it
|
|
23
|
+
* can say exactly:
|
|
24
|
+
*
|
|
25
|
+
* - **All of it**: every predicate compiles, and the sort is a bare field
|
|
26
|
+
* (`o => o.createdAt`) or there's none → one statement with WHERE, ORDER
|
|
27
|
+
* BY, LIMIT, OFFSET and the selected columns.
|
|
28
|
+
*
|
|
29
|
+
* - **The filter, not the sort**: the predicates compile but the sort is
|
|
30
|
+
* computed (`o => o.a.b`, `o => o.name.toLowerCase()`) → SQL selects the
|
|
31
|
+
* matching rows, and JS sorts, skips and takes them. A limit can't go into
|
|
32
|
+
* SQL without its order, so all the matching rows are read.
|
|
33
|
+
*
|
|
34
|
+
* - **None of it**: a predicate doesn't compile → every row is read (SELECT
|
|
35
|
+
* *), and the chain runs as JS array operations.
|
|
36
|
+
*
|
|
37
|
+
* A warning is logged whenever JS does part of the work, so developers can
|
|
38
|
+
* optimize. All three select the same rows in the same order; JS orders as
|
|
39
|
+
* SQLite does (`compareAsSqlite`). Without a sortBy, the order is SQLite's
|
|
40
|
+
* own: unspecified, except that `reverse()` and `last()` mean the reverse of
|
|
41
|
+
* the order rows were written in (`rowid`).
|
|
42
|
+
*/
|
|
43
|
+
import { type AggregateSelect, type AggregateRow, type NormalizedAggregateSpec } from './aggregate.js';
|
|
44
|
+
import type { Predicate, PredicateBindings, PredicateEntry, Accessor, TableConfig, SqlQuery, SqlResult } from './types.js';
|
|
45
|
+
type AggregateState<T> = {
|
|
46
|
+
kind: 'scalar';
|
|
47
|
+
fn: 'count' | 'sum' | 'avg' | 'countDistinct';
|
|
48
|
+
accessor?: Accessor<T>;
|
|
49
|
+
} | {
|
|
50
|
+
kind: 'grouped';
|
|
51
|
+
spec: NormalizedAggregateSpec;
|
|
52
|
+
};
|
|
53
|
+
export declare class Query<T, TResult = T[]> implements PromiseLike<TResult> {
|
|
54
|
+
private readonly _predicates;
|
|
55
|
+
private readonly _sortAccessor;
|
|
56
|
+
private readonly _reversed;
|
|
57
|
+
private readonly _limit;
|
|
58
|
+
private readonly _offset;
|
|
59
|
+
private readonly _config;
|
|
60
|
+
/** @internal Pre-compiled WHERE clause (bypasses predicate compiler). Used by Table.get(). */
|
|
61
|
+
private readonly _rawWhere;
|
|
62
|
+
private readonly _rawWhereParams;
|
|
63
|
+
/** @internal See AggregateState — set by aggregate terminals. */
|
|
64
|
+
private readonly _aggregate;
|
|
65
|
+
/** @internal The columns `select()` named; every column when unset. */
|
|
66
|
+
private readonly _columns;
|
|
67
|
+
/** @internal Post-process transform applied after row deserialization. */
|
|
68
|
+
readonly _postProcess: ((rows: T[]) => TResult) | undefined;
|
|
69
|
+
constructor(config: TableConfig, options?: {
|
|
70
|
+
predicates?: PredicateEntry<T>[];
|
|
71
|
+
sortAccessor?: Accessor<T>;
|
|
72
|
+
reversed?: boolean;
|
|
73
|
+
limit?: number;
|
|
74
|
+
offset?: number;
|
|
75
|
+
postProcess?: (rows: T[]) => TResult;
|
|
76
|
+
rawWhere?: string;
|
|
77
|
+
rawWhereParams?: unknown[];
|
|
78
|
+
aggregate?: AggregateState<T>;
|
|
79
|
+
columns?: string[];
|
|
80
|
+
});
|
|
81
|
+
private _clone;
|
|
82
|
+
filter(predicate: Predicate<T>): Query<T>;
|
|
83
|
+
filter<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Query<T>;
|
|
84
|
+
sortBy(accessor: Accessor<T>): Query<T>;
|
|
85
|
+
reverse(): Query<T>;
|
|
86
|
+
take(n: number): Query<T>;
|
|
87
|
+
skip(n: number): Query<T>;
|
|
88
|
+
/**
|
|
89
|
+
* Return only these columns: `SELECT id, name` rather than every column of
|
|
90
|
+
* a wide row. Chain it before a terminal (`first()`, `take()`); filters and
|
|
91
|
+
* sorts still see the whole row.
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* const names = await Companies
|
|
95
|
+
* .filter((c, $) => c.firmId === $.firmId, { firmId })
|
|
96
|
+
* .select('id', 'name');
|
|
97
|
+
* // Array<{ id: string; name: string }>
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
select<K extends keyof T & string>(...columns: K[]): Query<Pick<T, K>>;
|
|
101
|
+
first(): Query<T, T | null>;
|
|
102
|
+
last(): Query<T, T | null>;
|
|
103
|
+
count(): Query<T, number>;
|
|
104
|
+
/**
|
|
105
|
+
* Sum of a numeric field across matching rows. Compiles to a SQL
|
|
106
|
+
* aggregate (TOTAL) when possible — no rows are fetched. Returns 0 for
|
|
107
|
+
* an empty set; NULL values are skipped (SQL semantics).
|
|
108
|
+
*/
|
|
109
|
+
sum(accessor: Accessor<T, number | null | undefined>): Query<T, number>;
|
|
110
|
+
/**
|
|
111
|
+
* Average of a numeric field across matching rows. Compiles to SQL AVG
|
|
112
|
+
* when possible. Returns null for an empty set (or when every value is
|
|
113
|
+
* null) — SQL AVG semantics.
|
|
114
|
+
*/
|
|
115
|
+
avg(accessor: Accessor<T, number | null | undefined>): Query<T, number | null>;
|
|
116
|
+
/**
|
|
117
|
+
* Number of distinct non-null values of a field across matching rows.
|
|
118
|
+
* Compiles to SQL COUNT(DISTINCT col) when possible.
|
|
119
|
+
*/
|
|
120
|
+
countDistinct(accessor: Accessor<T>): Query<T, number>;
|
|
121
|
+
/**
|
|
122
|
+
* Multiple aggregates over all matching rows — a single result object.
|
|
123
|
+
* Compiles to one SQL aggregate statement; no rows are fetched.
|
|
124
|
+
*
|
|
125
|
+
* ```ts
|
|
126
|
+
* const stats = await Orders
|
|
127
|
+
* .filter(o => o.status === 'paid')
|
|
128
|
+
* .aggregate({ select: { n: { count: true }, revenue: { sum: 'amount' } } });
|
|
129
|
+
* // { n: number; revenue: number }
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
aggregate<S extends AggregateSelect<T>>(spec: {
|
|
133
|
+
select: S;
|
|
134
|
+
}): Query<T, AggregateRow<T, S>>;
|
|
135
|
+
/**
|
|
136
|
+
* Grouped aggregation — compiles to SELECT ... GROUP BY; never fetches
|
|
137
|
+
* rows (when the filter compiles to SQL). Returns one plain object per
|
|
138
|
+
* group: the group-key columns plus one property per select alias.
|
|
139
|
+
* `orderBy` names a select alias or group key; with `desc` + `limit`
|
|
140
|
+
* this expresses top-N groups in a single statement.
|
|
141
|
+
*
|
|
142
|
+
* ```ts
|
|
143
|
+
* const top = await Answers
|
|
144
|
+
* .filter((a, $) => a.surveyId === $.surveyId, { surveyId })
|
|
145
|
+
* .aggregate({
|
|
146
|
+
* by: ['questionId'],
|
|
147
|
+
* select: {
|
|
148
|
+
* n: { count: true },
|
|
149
|
+
* avgScore: { avg: 'score' },
|
|
150
|
+
* respondents: { countDistinct: 'responseId' },
|
|
151
|
+
* },
|
|
152
|
+
* orderBy: 'n',
|
|
153
|
+
* desc: true,
|
|
154
|
+
* limit: 20,
|
|
155
|
+
* });
|
|
156
|
+
* // Array<{ questionId: string; n: number; avgScore: number | null; respondents: number }>
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
aggregate<const By extends readonly (keyof T & string)[], S extends AggregateSelect<T>>(spec: {
|
|
160
|
+
by: By;
|
|
161
|
+
select: S;
|
|
162
|
+
orderBy?: (keyof S & string) | By[number];
|
|
163
|
+
desc?: boolean;
|
|
164
|
+
limit?: number;
|
|
165
|
+
}): Query<T, Array<Pick<T, By[number]> & AggregateRow<T, S>>>;
|
|
166
|
+
some(): Query<T, boolean>;
|
|
167
|
+
every(): Promise<boolean>;
|
|
168
|
+
min(accessor: Accessor<T, number>): Query<T, T | null>;
|
|
169
|
+
max(accessor: Accessor<T, number>): Query<T, T | null>;
|
|
170
|
+
groupBy<K extends string | number>(accessor: Accessor<T, K>): Query<T, Map<K, T[]>>;
|
|
171
|
+
/**
|
|
172
|
+
* @internal Compile this query into the statement to run, plus whatever
|
|
173
|
+
* JS has to do with its rows (see the module header's three cases). Used by
|
|
174
|
+
* db.batch() and by a standalone await alike.
|
|
175
|
+
*/
|
|
176
|
+
_compile(): CompiledQuery<T, TResult>;
|
|
177
|
+
/**
|
|
178
|
+
* @internal Process raw SQL results into typed rows. Used by db.batch()
|
|
179
|
+
* after executing the compiled query, and by a standalone await.
|
|
180
|
+
*
|
|
181
|
+
* Deserializes the rows, then does in JS whatever the SQL couldn't
|
|
182
|
+
* (`inJs`): the filter, the sort, the page, the projection.
|
|
183
|
+
*/
|
|
184
|
+
static _processResults<T, R = T[]>(result: SqlResult, compiled: CompiledQuery<T, R>): R;
|
|
185
|
+
/** @internal Say that part of a query ran in JS, and why. */
|
|
186
|
+
static _warnInJs<T, R>(compiled: CompiledQuery<T, R>, rowsRead?: number): void;
|
|
187
|
+
then<TResult1 = TResult, TResult2 = never>(onfulfilled?: ((value: TResult) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
188
|
+
private _run;
|
|
189
|
+
/**
|
|
190
|
+
* @internal Compile the pending aggregate into a single SQL statement +
|
|
191
|
+
* result processor. Returns null (→ fetch path, postProcess computes the
|
|
192
|
+
* aggregate) when there is no aggregate, when a pre-compiled WHERE is in
|
|
193
|
+
* play (Table.get()), when limit/offset are set (aggregate-the-page
|
|
194
|
+
* semantics — COUNT(*)/TOTAL can't express "over the limited page"), or
|
|
195
|
+
* when a scalar accessor doesn't extract to a column (computed accessors
|
|
196
|
+
* stay correct via JS, with a warning to prompt optimization).
|
|
197
|
+
*/
|
|
198
|
+
private _compileAggregateSql;
|
|
199
|
+
catch<TResult2 = never>(onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult | TResult2>;
|
|
200
|
+
private _compilePredicates;
|
|
201
|
+
private _fetchAllRows;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Result of Query._compile(): the statement to run, and what's left to do in
|
|
205
|
+
* JS over its rows when SQL couldn't do all of it.
|
|
206
|
+
*/
|
|
207
|
+
export interface CompiledQuery<T, TResult = T[]> {
|
|
208
|
+
type: 'query';
|
|
209
|
+
/** The statement to run. */
|
|
210
|
+
query: SqlQuery;
|
|
211
|
+
/** Table config for deserialization. */
|
|
212
|
+
config: TableConfig;
|
|
213
|
+
/** What JS does to the statement's rows, in order, when SQL couldn't. */
|
|
214
|
+
inJs?: {
|
|
215
|
+
/** Why, for the warning. */
|
|
216
|
+
why: string;
|
|
217
|
+
/** Filters SQL couldn't run (the statement then reads every row). */
|
|
218
|
+
predicates?: PredicateEntry<T>[];
|
|
219
|
+
sortAccessor?: Accessor<T>;
|
|
220
|
+
reversed: boolean;
|
|
221
|
+
limit?: number;
|
|
222
|
+
offset?: number;
|
|
223
|
+
/** The columns `select()` named, kept once the rest is done. */
|
|
224
|
+
columns?: string[];
|
|
225
|
+
};
|
|
226
|
+
/** Post-process transform (e.g. first() extracts [0] ?? null). */
|
|
227
|
+
postProcess?: (rows: T[]) => TResult;
|
|
228
|
+
/** When set, the SQL result rows ARE the answer (aggregate values, not
|
|
229
|
+
* table rows): called instead of deserialize + postProcess. */
|
|
230
|
+
processRaw?: (result: SqlResult) => TResult;
|
|
231
|
+
}
|
|
232
|
+
export declare function extractFieldName<T>(accessor: Accessor<T>): string | null;
|
|
233
|
+
export {};
|
package/dist/db/raw.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RawQuery — the lazy result of `db.sql()`, the read-only raw-SQL escape
|
|
3
|
+
* hatch. Like Mutation, it's a fixed statement with a result processor:
|
|
4
|
+
* awaiting executes it; passing it to `db.batch()` bundles it with typed
|
|
5
|
+
* Query/Mutation operations in one round trip.
|
|
6
|
+
*
|
|
7
|
+
* The read-only gate (SELECT/WITH only) lives in `db.sql()` itself — by the
|
|
8
|
+
* time a RawQuery exists, the statement has passed it.
|
|
9
|
+
*/
|
|
10
|
+
import type { SqlQuery, SqlResult } from './types.js';
|
|
11
|
+
export interface CompiledRawQuery<TResult> {
|
|
12
|
+
type: 'raw';
|
|
13
|
+
query: SqlQuery;
|
|
14
|
+
/** Only databaseId — that's all batch grouping reads from config. */
|
|
15
|
+
config: {
|
|
16
|
+
databaseId: string;
|
|
17
|
+
};
|
|
18
|
+
processResult: (result: SqlResult) => TResult;
|
|
19
|
+
}
|
|
20
|
+
export declare class RawQuery<TResult = Record<string, unknown>[]> implements PromiseLike<TResult> {
|
|
21
|
+
/** Read when it's compiled: the lazy db's database is known only once its context is. */
|
|
22
|
+
private readonly _databaseId;
|
|
23
|
+
private readonly _executeBatch;
|
|
24
|
+
private readonly _query;
|
|
25
|
+
constructor(databaseId: () => string, executeBatch: (queries: SqlQuery[]) => Promise<SqlResult[]>, query: SqlQuery);
|
|
26
|
+
then<T1 = TResult, T2 = never>(onfulfilled?: ((value: TResult) => T1 | PromiseLike<T1>) | null, onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<T1 | T2>;
|
|
27
|
+
catch<T2 = never>(onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<TResult | T2>;
|
|
28
|
+
/** @internal Compile for db.batch(). */
|
|
29
|
+
_compile(): CompiledRawQuery<TResult>;
|
|
30
|
+
/** @internal Process a raw SQL result. Used by db.batch(). */
|
|
31
|
+
static _processResults<T>(result: SqlResult, compiled: CompiledRawQuery<T>): T;
|
|
32
|
+
/** Schema-less deserialization: strips @@user@@ prefixes and best-effort
|
|
33
|
+
* parses JSON-looking strings; makes no other representation promises. */
|
|
34
|
+
private static _process;
|
|
35
|
+
private _execute;
|
|
36
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-tick reads share a round trip.
|
|
3
|
+
*
|
|
4
|
+
* Every database call is a frame to the platform, and each frame pays a fixed
|
|
5
|
+
* cost there (its credential, the database's owner, a turn on the database)
|
|
6
|
+
* however small its statements. A method that starts several reads at once
|
|
7
|
+
* (`Promise.all` of queries, a handful of `findOne`s for a page) used to send
|
|
8
|
+
* each as its own frame. Here, the reads one request starts against one
|
|
9
|
+
* database in the same tick go as one batch, and each caller gets its own
|
|
10
|
+
* slice of the results.
|
|
11
|
+
*
|
|
12
|
+
* Reads only, and only one request's: a batch is one transaction on the pod,
|
|
13
|
+
* and a write would take the reads beside it into its atomicity and its
|
|
14
|
+
* retry rule; the request's credential decides who the statements run as.
|
|
15
|
+
* A write first sends the reads queued before it, so they keep their order.
|
|
16
|
+
*
|
|
17
|
+
* Identical reads already on their way (the same statements, from the same
|
|
18
|
+
* request) share one answer, each caller getting its own copy. That's never
|
|
19
|
+
* a cached result: once a read has answered, the next one runs again.
|
|
20
|
+
*
|
|
21
|
+
* If a merged batch fails, each caller's reads run again on their own, so a
|
|
22
|
+
* caller hears its own error, not a neighbour's (a read is safe to repeat).
|
|
23
|
+
*/
|
|
24
|
+
import type { SqlQuery, SqlResult } from './types.js';
|
|
25
|
+
type Send = (databaseId: string, queries: SqlQuery[]) => Promise<SqlResult[]>;
|
|
26
|
+
export declare class DbReadBatching {
|
|
27
|
+
private readonly send;
|
|
28
|
+
private readonly pending;
|
|
29
|
+
private readonly inFlight;
|
|
30
|
+
constructor(send: Send);
|
|
31
|
+
/** Run `queries` for the request holding `token`, sharing a round trip where it can. */
|
|
32
|
+
run(token: string, databaseId: string, queries: SqlQuery[]): Promise<SqlResult[]>;
|
|
33
|
+
private queue;
|
|
34
|
+
private flush;
|
|
35
|
+
}
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whole-table reads the platform reports beside a batch's results: a statement
|
|
3
|
+
* that took a while because it read every row of a table, which an index on
|
|
4
|
+
* the columns it filters or sorts by (`defineTable`'s `indexes`) would make a
|
|
5
|
+
* lookup. The platform reports one for a slow statement at most once every 15
|
|
6
|
+
* minutes, so the line is a hint, not a count.
|
|
7
|
+
*/
|
|
8
|
+
export declare function warnTableScans(scans: unknown): void;
|
package/dist/db/sql.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL builders for the `db` namespace.
|
|
3
|
+
*
|
|
4
|
+
* Pure functions that generate SQL strings with `?` placeholder bind params
|
|
5
|
+
* for SQLite. These are used by Table and Query to translate collection
|
|
6
|
+
* operations into queries executed via `POST /_internal/v2/db/query`.
|
|
7
|
+
*
|
|
8
|
+
* ## Parameterized queries
|
|
9
|
+
*
|
|
10
|
+
* All builders return `{ sql, params }` tuples. Every value is a positional
|
|
11
|
+
* bind param (`?`), never inlined into the SQL string, the compiled filters'
|
|
12
|
+
* included (`predicate.ts`), so a statement's shape doesn't change with its
|
|
13
|
+
* values. Only identifiers (table and column names) are written into the SQL.
|
|
14
|
+
*
|
|
15
|
+
* ## RETURNING support
|
|
16
|
+
*
|
|
17
|
+
* INSERT and UPDATE builders append `RETURNING *` so the platform returns
|
|
18
|
+
* the created/updated row in a single round trip — no separate SELECT needed.
|
|
19
|
+
*
|
|
20
|
+
* ## User type columns
|
|
21
|
+
*
|
|
22
|
+
* Columns with schema type `'user'` store values with a `@@user@@` prefix
|
|
23
|
+
* in SQLite (e.g. `@@user@@550e8400-...`). The `serializeParam()` and
|
|
24
|
+
* `deserializeRow()` functions handle this transparently — application
|
|
25
|
+
* code always works with clean UUID strings.
|
|
26
|
+
*/
|
|
27
|
+
import type { AppDatabaseColumnSchema } from '../types.js';
|
|
28
|
+
import type { SqlQuery } from './types.js';
|
|
29
|
+
/**
|
|
30
|
+
* Serialize a JavaScript value for use as a bind param.
|
|
31
|
+
*
|
|
32
|
+
* - `null` / `undefined` → `null`
|
|
33
|
+
* - `boolean` → `1` or `0` (SQLite convention)
|
|
34
|
+
* - `number` / `string` → passed through
|
|
35
|
+
* - `object` / `array` → JSON-encoded string
|
|
36
|
+
*/
|
|
37
|
+
export declare function serializeParam(val: unknown): unknown;
|
|
38
|
+
/**
|
|
39
|
+
* Serialize a value for a specific column, handling the @@user@@ prefix
|
|
40
|
+
* for user-type columns.
|
|
41
|
+
*
|
|
42
|
+
* Idempotent: if a caller passes an already-prefixed value (e.g. from a raw
|
|
43
|
+
* SQL read or a cross-path copy), we don't double-prefix it.
|
|
44
|
+
*/
|
|
45
|
+
export declare function serializeColumnParam(val: unknown, columnName: string, columns: AppDatabaseColumnSchema[]): unknown;
|
|
46
|
+
export declare const USER_PREFIX = "@@user@@";
|
|
47
|
+
/**
|
|
48
|
+
* Deserialize a row from the database, handling:
|
|
49
|
+
* - Stripping `@@user@@` prefix from any string value that carries it
|
|
50
|
+
* (platform-managed audit columns like `last_updated_by` are sometimes
|
|
51
|
+
* typed as `text` in schema metadata but still store user refs with the
|
|
52
|
+
* prefix — strip defensively so app code always sees bare UUIDs)
|
|
53
|
+
* - Parsing JSON strings for json-type columns
|
|
54
|
+
*/
|
|
55
|
+
export declare function deserializeRow(row: Record<string, unknown>, columns: AppDatabaseColumnSchema[]): Record<string, unknown>;
|
|
56
|
+
/**
|
|
57
|
+
* Compare two deserialized values the way SQLite's ORDER BY does: NULL
|
|
58
|
+
* first, then numbers (a boolean as its stored 0 or 1), then text (a parsed
|
|
59
|
+
* json value as its JSON), then blobs. So rows sorted in JS, by a computed
|
|
60
|
+
* key or after a fallback, come back in the order SQL would have given.
|
|
61
|
+
*/
|
|
62
|
+
export declare function compareAsSqlite(a: unknown, b: unknown): number;
|
|
63
|
+
export interface SelectOptions {
|
|
64
|
+
/** The columns to return, all of them when unset. */
|
|
65
|
+
columns?: string[];
|
|
66
|
+
/** WHERE clause (with ? placeholders). */
|
|
67
|
+
where?: string;
|
|
68
|
+
/** Params for the WHERE clause. */
|
|
69
|
+
whereParams?: unknown[];
|
|
70
|
+
/** A column, or `rowid` for the order rows were written in. */
|
|
71
|
+
orderBy?: string;
|
|
72
|
+
desc?: boolean;
|
|
73
|
+
limit?: number;
|
|
74
|
+
offset?: number;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Build a SELECT query with bind params. An offset with no limit is `LIMIT -1`
|
|
78
|
+
* (no limit), since SQLite has no OFFSET without one.
|
|
79
|
+
*/
|
|
80
|
+
export declare function buildSelect(table: string, options?: SelectOptions): SqlQuery;
|
|
81
|
+
export type AggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max' | 'countDistinct';
|
|
82
|
+
export declare function assertSqlIdentifier(name: string, context: string): void;
|
|
83
|
+
/**
|
|
84
|
+
* Build a single-value aggregate: SELECT <expr> AS value FROM t [WHERE ...].
|
|
85
|
+
* Used by count()/sum()/avg()/countDistinct() terminals.
|
|
86
|
+
*/
|
|
87
|
+
export declare function buildScalarAggregate(table: string, fn: AggregateFn, column: string | null, where?: string, whereParams?: unknown[]): SqlQuery;
|
|
88
|
+
/**
|
|
89
|
+
* Build a grouped aggregate:
|
|
90
|
+
* SELECT by..., <expr AS alias>... FROM t [WHERE] [GROUP BY by...]
|
|
91
|
+
* [ORDER BY key [DESC]] [LIMIT n].
|
|
92
|
+
* With an empty `by`, this is a whole-set multi-aggregate returning one row.
|
|
93
|
+
*/
|
|
94
|
+
export declare function buildGroupedAggregate(table: string, options: {
|
|
95
|
+
by: string[];
|
|
96
|
+
select: {
|
|
97
|
+
alias: string;
|
|
98
|
+
fn: AggregateFn;
|
|
99
|
+
column?: string;
|
|
100
|
+
}[];
|
|
101
|
+
where?: string;
|
|
102
|
+
whereParams?: unknown[];
|
|
103
|
+
orderBy?: string;
|
|
104
|
+
desc?: boolean;
|
|
105
|
+
limit?: number;
|
|
106
|
+
}): SqlQuery;
|
|
107
|
+
/**
|
|
108
|
+
* Build a SELECT EXISTS query. Used for `.some()` and `.every()`.
|
|
109
|
+
*/
|
|
110
|
+
export declare function buildExists(table: string, where?: string, whereParams?: unknown[], negate?: boolean): SqlQuery;
|
|
111
|
+
/**
|
|
112
|
+
* Build an INSERT statement with RETURNING *.
|
|
113
|
+
* `id` is never sent (`stripPlatformColumns`); the platform's triggers fill in
|
|
114
|
+
* whichever other system columns the data leaves out.
|
|
115
|
+
* Values are passed as bind params.
|
|
116
|
+
*/
|
|
117
|
+
export declare function buildInsert(table: string, data: Record<string, unknown>, columns: AppDatabaseColumnSchema[]): SqlQuery;
|
|
118
|
+
/**
|
|
119
|
+
* Build an UPDATE statement with RETURNING *.
|
|
120
|
+
* `id` is never sent; `updated_at` and `last_updated_by` are the platform's
|
|
121
|
+
* unless the data sets them. Values are bind params.
|
|
122
|
+
*/
|
|
123
|
+
export declare function buildUpdate(table: string, id: string, data: Record<string, unknown>, columns: AppDatabaseColumnSchema[]): SqlQuery;
|
|
124
|
+
/**
|
|
125
|
+
* Build an INSERT ... ON CONFLICT ... DO UPDATE statement with RETURNING *.
|
|
126
|
+
* `id` is never sent; a system column the data sets is applied on both
|
|
127
|
+
* branches, like any other. Values are bind params.
|
|
128
|
+
*
|
|
129
|
+
* If all data keys are conflict columns (nothing to update), uses DO NOTHING.
|
|
130
|
+
* Uses SQLite's `excluded.` prefix to reference the attempted INSERT values.
|
|
131
|
+
*/
|
|
132
|
+
export declare function buildUpsert(table: string, data: Record<string, unknown>, conflictColumns: string[], columns: AppDatabaseColumnSchema[]): SqlQuery;
|
|
133
|
+
/**
|
|
134
|
+
* Build a DELETE statement.
|
|
135
|
+
*/
|
|
136
|
+
export declare function buildDelete(table: string, where?: string, whereParams?: unknown[]): SqlQuery;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Table<T> — a typed persistent collection backed by SQLite.
|
|
3
|
+
*
|
|
4
|
+
* Created via `db.defineTable<T>(name)`. Every method either returns a
|
|
5
|
+
* chainable Query<T> (for lazy reads), a Mutation<T> (for lazy writes),
|
|
6
|
+
* or a Promise (for terminal reads).
|
|
7
|
+
*
|
|
8
|
+
* ## Write operations use RETURNING
|
|
9
|
+
*
|
|
10
|
+
* INSERT and UPDATE use `RETURNING *` to get the created/updated row
|
|
11
|
+
* back in a single round trip — no separate SELECT needed. This is
|
|
12
|
+
* executed via the batch endpoint which runs all queries on a single
|
|
13
|
+
* SQLite connection.
|
|
14
|
+
*/
|
|
15
|
+
import { Query } from './query.js';
|
|
16
|
+
import { Mutation } from './mutation.js';
|
|
17
|
+
import type { Predicate, PredicateBindings, Accessor, PushInput, UpdateInput, SystemFields, TableConfig } from './types.js';
|
|
18
|
+
import type { AggregateSelect, AggregateRow } from './aggregate.js';
|
|
19
|
+
export declare class Table<T> {
|
|
20
|
+
/** @internal */
|
|
21
|
+
private readonly _config;
|
|
22
|
+
constructor(config: TableConfig);
|
|
23
|
+
/** Get a single row by ID. Returns null if not found. */
|
|
24
|
+
get(id: string): Query<T, T | null>;
|
|
25
|
+
/** Find the first row matching a predicate. Returns null if none match. */
|
|
26
|
+
findOne(predicate: Predicate<T>): Query<T, T | null>;
|
|
27
|
+
findOne<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Query<T, T | null>;
|
|
28
|
+
/** Count all rows, or rows matching a predicate. */
|
|
29
|
+
count(): Query<T, number>;
|
|
30
|
+
count(predicate: Predicate<T>): Query<T, number>;
|
|
31
|
+
count<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Query<T, number>;
|
|
32
|
+
/** True if any row matches the predicate. */
|
|
33
|
+
some(predicate: Predicate<T>): Query<T, boolean>;
|
|
34
|
+
some<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Query<T, boolean>;
|
|
35
|
+
/** True if all rows match the predicate. */
|
|
36
|
+
every(predicate: Predicate<T>): Promise<boolean>;
|
|
37
|
+
every<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Promise<boolean>;
|
|
38
|
+
/** True if the table has zero rows. */
|
|
39
|
+
isEmpty(): Promise<boolean>;
|
|
40
|
+
/** Row with the minimum value for a field, or null if table is empty. */
|
|
41
|
+
min(accessor: Accessor<T, number>): Query<T, T | null>;
|
|
42
|
+
/** Row with the maximum value for a field, or null if table is empty. */
|
|
43
|
+
max(accessor: Accessor<T, number>): Query<T, T | null>;
|
|
44
|
+
/**
|
|
45
|
+
* Sum of a numeric field across all rows (0 for an empty table).
|
|
46
|
+
* Runs as a SQL aggregate — no rows are fetched. Chain from filter()
|
|
47
|
+
* to sum a subset: `Orders.filter(...).sum(o => o.amount)`.
|
|
48
|
+
*/
|
|
49
|
+
sum(accessor: Accessor<T, number | null | undefined>): Query<T, number>;
|
|
50
|
+
/**
|
|
51
|
+
* Average of a numeric field across all rows (null for an empty table).
|
|
52
|
+
* Runs as a SQL aggregate — no rows are fetched.
|
|
53
|
+
*/
|
|
54
|
+
avg(accessor: Accessor<T, number | null | undefined>): Query<T, number | null>;
|
|
55
|
+
/**
|
|
56
|
+
* Number of distinct non-null values of a field across all rows.
|
|
57
|
+
* Runs as a SQL aggregate — no rows are fetched.
|
|
58
|
+
*/
|
|
59
|
+
countDistinct(accessor: Accessor<T>): Query<T, number>;
|
|
60
|
+
/**
|
|
61
|
+
* Grouped (or whole-table) aggregation compiling to a single SQL
|
|
62
|
+
* statement — see Query.aggregate() for the spec shape and examples.
|
|
63
|
+
*/
|
|
64
|
+
aggregate<S extends AggregateSelect<T>>(spec: {
|
|
65
|
+
select: S;
|
|
66
|
+
}): Query<T, AggregateRow<T, S>>;
|
|
67
|
+
aggregate<const By extends readonly (keyof T & string)[], S extends AggregateSelect<T>>(spec: {
|
|
68
|
+
by: By;
|
|
69
|
+
select: S;
|
|
70
|
+
orderBy?: (keyof S & string) | By[number];
|
|
71
|
+
desc?: boolean;
|
|
72
|
+
limit?: number;
|
|
73
|
+
}): Query<T, Array<Pick<T, By[number]> & AggregateRow<T, S>>>;
|
|
74
|
+
/** Group rows by a field. Returns a Map of FULL rows per group — it
|
|
75
|
+
* fetches everything. For grouped counts/sums/averages over tables that
|
|
76
|
+
* can grow large, use `aggregate()` instead (SQL GROUP BY, no row fetch). */
|
|
77
|
+
groupBy<K extends string | number>(accessor: Accessor<T, K>): Query<T, Map<K, T[]>>;
|
|
78
|
+
/** Get all rows as an array. */
|
|
79
|
+
toArray(): Query<T>;
|
|
80
|
+
/** Filter rows by a predicate. Returns a chainable Query. */
|
|
81
|
+
filter(predicate: Predicate<T>): Query<T>;
|
|
82
|
+
filter<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Query<T>;
|
|
83
|
+
/** Sort rows by a field. Returns a chainable Query. */
|
|
84
|
+
sortBy(accessor: Accessor<T>): Query<T>;
|
|
85
|
+
/** Every row, with only these columns. See Query.select(). */
|
|
86
|
+
select<K extends keyof T & string>(...columns: K[]): Query<Pick<T, K>>;
|
|
87
|
+
/**
|
|
88
|
+
* Insert one or more rows. Returns the created row(s) with system fields
|
|
89
|
+
* populated (id, created_at, updated_at, last_updated_by).
|
|
90
|
+
*
|
|
91
|
+
* A row may give its own `created_at`, `updated_at` and `last_updated_by`
|
|
92
|
+
* (an import, a scenario's history); the platform fills in whichever it
|
|
93
|
+
* leaves out, and always generates `id`. So a row spread from one read
|
|
94
|
+
* back (`push({ ...row, name })`) keeps that row's dates and author.
|
|
95
|
+
*
|
|
96
|
+
* Uses `INSERT ... RETURNING *` so the created row comes back in a
|
|
97
|
+
* single round trip — no separate SELECT needed.
|
|
98
|
+
*/
|
|
99
|
+
push(data: PushInput<T>): Mutation<T>;
|
|
100
|
+
push(data: PushInput<T>[]): Mutation<T[]>;
|
|
101
|
+
/**
|
|
102
|
+
* Update a row by ID. Only the provided fields are changed.
|
|
103
|
+
* Returns the updated row via `UPDATE ... RETURNING *`.
|
|
104
|
+
*
|
|
105
|
+
* The platform advances `updated_at` and stamps `last_updated_by` with the
|
|
106
|
+
* signed-in user unless the data changes them itself.
|
|
107
|
+
*/
|
|
108
|
+
update(id: string, data: UpdateInput<T>): Mutation<T>;
|
|
109
|
+
remove(id: string): Mutation<{
|
|
110
|
+
deleted: boolean;
|
|
111
|
+
}>;
|
|
112
|
+
/**
|
|
113
|
+
* Remove all rows matching a predicate. Returns the count removed.
|
|
114
|
+
*/
|
|
115
|
+
removeAll(predicate: Predicate<T>): Mutation<number>;
|
|
116
|
+
removeAll<B extends PredicateBindings>(predicate: (row: T, bindings: B) => boolean, bindings: B): Mutation<number>;
|
|
117
|
+
clear(): Mutation<number>;
|
|
118
|
+
/**
|
|
119
|
+
* Insert a row, or update it if a row with the same unique key already
|
|
120
|
+
* exists. The conflict key must match a `unique` constraint declared in
|
|
121
|
+
* defineTable options. Returns the created or updated row.
|
|
122
|
+
*
|
|
123
|
+
* Uses SQLite's `INSERT ... ON CONFLICT ... DO UPDATE SET ... RETURNING *`.
|
|
124
|
+
*
|
|
125
|
+
* @param conflictKey - Column name(s) that form the unique constraint.
|
|
126
|
+
* Pass a single string for single-column unique, or an array for compound.
|
|
127
|
+
* @param data - Row data to insert (or update on conflict). Defaults apply.
|
|
128
|
+
* A `created_at`, `updated_at` or `last_updated_by` it gives is written
|
|
129
|
+
* either way; whichever it leaves out the platform fills in.
|
|
130
|
+
*/
|
|
131
|
+
upsert(conflictKey: (keyof Omit<T, SystemFields> & string) | (keyof Omit<T, SystemFields> & string)[], data: PushInput<T>): Mutation<T>;
|
|
132
|
+
/**
|
|
133
|
+
* @internal Throw if data writes the auth table's API key column, which holds
|
|
134
|
+
* the masked key the platform issued. The other mapped columns are the app's
|
|
135
|
+
* to write.
|
|
136
|
+
*/
|
|
137
|
+
private _checkApiKeyWrite;
|
|
138
|
+
/**
|
|
139
|
+
* @internal Fire role sync for rows that wrote to the roles column.
|
|
140
|
+
* Called inside processResult (runs after SQL execution in both
|
|
141
|
+
* standalone and batch paths). Fire-and-forget.
|
|
142
|
+
*/
|
|
143
|
+
private _syncRolesIfNeeded;
|
|
144
|
+
/** @internal Validate that the given columns match a declared unique constraint. */
|
|
145
|
+
private _validateUniqueConstraint;
|
|
146
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `db` namespace's time helpers. Pure JS, all unix ms.
|
|
3
|
+
*
|
|
4
|
+
* One definition for both `db` objects (the lazy one on the agent and
|
|
5
|
+
* `createDb`'s), and the one the predicate compiler evaluates when a filter
|
|
6
|
+
* compares against a helper call (`o.createdAt > db.ago(db.days(7))`), so the
|
|
7
|
+
* value it compiles to is the one the function would compute.
|
|
8
|
+
*/
|
|
9
|
+
export declare const timeHelpers: {
|
|
10
|
+
now: () => number;
|
|
11
|
+
days: (n: number) => number;
|
|
12
|
+
hours: (n: number) => number;
|
|
13
|
+
minutes: (n: number) => number;
|
|
14
|
+
ago: (ms: number) => number;
|
|
15
|
+
fromNow: (ms: number) => number;
|
|
16
|
+
};
|
|
17
|
+
export type TimeHelperName = keyof typeof timeHelpers;
|