@wavehouse/sdk 0.0.0-dev.0f8826c → 0.0.0-dev.h04a85f20bb96

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.cts CHANGED
@@ -1,7 +1,9 @@
1
1
  /** User-provided database schema mapping table names to row types. */
2
2
  type Database = Record<string, Record<string, unknown>>;
3
3
  /**
4
- * Discriminated union for all async SDK operations. Never throws.
4
+ * Discriminated union for all async SDK operations. Never throws for anything
5
+ * the server returns — caller and environment errors (a non-absolute `baseURL`,
6
+ * a missing `EventSource`, a rejecting `auth` callback) do throw.
5
7
  *
6
8
  * Discriminated on `ok`: `if (result.ok)` narrows to the success arm (and tells
7
9
  * the compiler `data` is present), while `error` is always available for
@@ -47,19 +49,117 @@ interface StreamSubscriber<T = Record<string, unknown>> {
47
49
  error?: (err: WaveHouseError) => void;
48
50
  }
49
51
  interface ClientConfig<_DB extends Database = Database> {
50
- /** Base URL of the WaveHouse server (e.g. "http://localhost:8080"). */
52
+ /**
53
+ * Base URL of the WaveHouse server (e.g. "http://localhost:8080"). May include
54
+ * a path prefix ("https://app.example.com/api/warehouse") for a WaveHouse
55
+ * behind a backend-for-frontend (BFF), app-server route, or path-routed
56
+ * ingress; request paths are appended to it. The proxy in front must strip
57
+ * the prefix before forwarding.
58
+ *
59
+ * Must be **absolute** — scheme and host included. The transports report a
60
+ * relative value such as "/api/warehouse" differently: a REST call rejects
61
+ * with a `TypeError` instead of returning a `Result`, while a stream reports
62
+ * `SSE_CONNECT_ERROR` to the subscriber's `error` callback. Build an absolute
63
+ * one: `` `${location.origin}/api/warehouse` ``.
64
+ */
51
65
  baseURL: string;
52
66
  /** Auth token provider. Omit for public/unauthenticated access. */
53
67
  auth?: () => Promise<string> | string;
54
68
  /** Additional client options. */
55
69
  options?: ClientOptions;
56
70
  }
71
+ /**
72
+ * A `fetch`-compatible function.
73
+ *
74
+ * Spelled out rather than written `typeof fetch`, which resolves differently
75
+ * depending on whether the consumer's TypeScript `lib` includes DOM — the same
76
+ * signature either way, but stable across configurations.
77
+ *
78
+ * In practice the SDK only ever calls it with a string URL, and reads `.ok` and
79
+ * `.headers` always, `.text()` on success, and `.status`, `.statusText` plus
80
+ * `.json()` when the response is not `ok`. A rejection becomes a
81
+ * `NETWORK_ERROR` result and is retried with backoff — except a `DOMException`
82
+ * named `AbortError` (what the platform `fetch` and undici throw on abort),
83
+ * which becomes `ABORTED` and is not retried. Implementations that reject with
84
+ * some other abort error, such as `node-fetch`, are retried instead.
85
+ *
86
+ * Implementations shipping their own request/response declarations (undici,
87
+ * `node-fetch`) need casts on the URL, the init and the return value, since
88
+ * those types are separate from the ones behind your global `fetch`; the
89
+ * narrow runtime contract above is what makes them safe.
90
+ */
91
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
57
92
  interface ClientOptions {
58
93
  /** Maximum retry attempts for failed requests. Default: 2. */
59
94
  maxRetries?: number;
95
+ /**
96
+ * HTTP implementation used for every REST request (SSE streams excluded).
97
+ * Defaults to the global `fetch`.
98
+ *
99
+ * Provide one to route through a proxy, attach client certificates, add
100
+ * middleware (logging, tracing, circuit breaking), or bypass a transport bug
101
+ * in the runtime's bundled HTTP stack by routing through an implementation
102
+ * you install yourself — e.g. an undici new enough to be free of
103
+ * {@link https://github.com/nodejs/undici/issues/5600 | undici #5600}:
104
+ *
105
+ * ```ts
106
+ * import { Agent, fetch as undiciFetch } from "undici"; // npm install undici — 8.10.0+
107
+ * // Pass the dispatcher explicitly: undici's pool lives on a shared
108
+ * // globalThis symbol claimed by whichever copy loaded first, so an implied
109
+ * // dispatcher can still be the runtime's affected one.
110
+ * const dispatcher = new Agent();
111
+ * createClient({
112
+ * baseURL,
113
+ * options: {
114
+ * fetch: (url, init) =>
115
+ * undiciFetch(url as string, { ...init, dispatcher } as never) as unknown as Promise<Response>,
116
+ * },
117
+ * });
118
+ * ```
119
+ *
120
+ * Only the SSE transport is exempt: the live connection behind `.stream()`
121
+ * and `.liveQuery()` uses `EventSource`, which this does not replace.
122
+ * `.liveQuery()`'s initial backfill is an ordinary request and does go
123
+ * through your function.
124
+ */
125
+ fetch?: FetchLike;
126
+ /**
127
+ * Headers added to every REST request (SSE streams excluded) — for a
128
+ * header-gated proxy in front of WaveHouse, such as a Cloudflare Access
129
+ * service token.
130
+ *
131
+ * Matched case-insensitively, as HTTP headers are. Applied underneath the
132
+ * SDK's own headers: `auth` still owns `Authorization`, and the
133
+ * `Content-Type` and `Accept` a given request needs are not overridable
134
+ * here — a global `Content-Type` that outranked the request's own is a
135
+ * documented way to break uploads.
136
+ */
137
+ headers?: Record<string, string>;
138
+ /**
139
+ * Extra `RequestInit` fields merged into every REST request — `credentials`
140
+ * for a cookie-authenticated origin, `mode`, `cache`, `keepalive`, or a
141
+ * runtime-specific extension such as Next.js's `next: { tags }`.
142
+ *
143
+ * Fields the SDK controls (`method`, `headers`, `body`, `signal`) always
144
+ * win, so this cannot corrupt the request itself. Non-standard fields may
145
+ * need a cast, since `RequestInit` only declares the standard ones.
146
+ */
147
+ fetchOptions?: RequestInit;
60
148
  }
61
149
  interface StructuredQuery {
150
+ /**
151
+ * Explicit columns to project. A literal "*" is a column named "*", not a
152
+ * wildcard. Omitting columns (with no aggregations and no select_all) selects
153
+ * nothing — use select_all for a full-row read. Mutually exclusive with
154
+ * select_all.
155
+ */
62
156
  columns?: string[];
157
+ /**
158
+ * Request every column the caller's role may read (the all-columns wildcard,
159
+ * expanded server-side to the allowed/denied set). Mutually exclusive with a
160
+ * non-empty columns list.
161
+ */
162
+ select_all?: boolean;
63
163
  aggregations?: Aggregation[];
64
164
  filters?: QueryFilter[];
65
165
  group_by?: string[];
@@ -97,9 +197,36 @@ interface TableSchema {
97
197
  columns: Column[];
98
198
  }
99
199
  type Schemas = Record<string, TableSchema>;
200
+ /**
201
+ * A per-record outcome from a batch (array / NDJSON) insert. Mirrors the
202
+ * single-object response shape plus the record's position. Exactly one of
203
+ * `ok` / `duplicate` / `error` is set.
204
+ */
205
+ interface InsertRecordResult {
206
+ /** 1-based index of the record within the submitted batch. */
207
+ index: number;
208
+ /** Set when the record was validated and published. */
209
+ ok?: boolean;
210
+ /** Set when dedup skipped the record. */
211
+ duplicate?: boolean;
212
+ /** Set (with `ok`/`duplicate` absent) when the record was rejected. */
213
+ error?: string;
214
+ }
100
215
  interface InsertResult {
216
+ /** True for a fully successful insert: a single row, or a batch with no rejected records (`failed === 0`). */
101
217
  ok: boolean;
218
+ /** Single insert only: set when dedup skipped the row. */
102
219
  duplicate?: boolean;
220
+ /** Batch insert (array / NDJSON): number of records submitted. */
221
+ total?: number;
222
+ /** Batch insert: records validated and published. */
223
+ succeeded?: number;
224
+ /** Batch insert: records rejected — see `results`. */
225
+ failed?: number;
226
+ /** Batch insert: records skipped by dedup. */
227
+ duplicates?: number;
228
+ /** Batch insert: per-record outcomes, each `{index, ok|duplicate|error}` (may be truncated for very large batches; the counts stay authoritative). */
229
+ results?: InsertRecordResult[];
103
230
  }
104
231
  interface DLQStats {
105
232
  tables: Record<string, number>;
@@ -133,8 +260,22 @@ interface RolePermissions {
133
260
  check?: Record<string, PolicyFilter>;
134
261
  allowed_aggregations?: string[];
135
262
  denied_aggregations?: string[];
263
+ /** Caps the query result LIMIT. 0 = no limit. */
136
264
  max_rows?: number;
137
- max_execution_time_ms?: number;
265
+ /**
266
+ * Max query execution time, enforced server-side by ClickHouse. Set it as a
267
+ * duration string ("5s", "500ms") or a number of milliseconds; reads always
268
+ * return the number of milliseconds.
269
+ */
270
+ max_execution_time?: number | string;
271
+ /** Max rows scanned from storage, enforced server-side by ClickHouse. 0 = no limit. */
272
+ max_rows_to_read?: number;
273
+ /**
274
+ * Max peak query memory, enforced server-side by ClickHouse. Set it as a size
275
+ * string ("4GiB", "512MiB") or a number of bytes; reads always return the
276
+ * number of bytes.
277
+ */
278
+ max_memory_usage?: number | string;
138
279
  }
139
280
  interface PolicyFilter {
140
281
  _eq?: string;
@@ -146,10 +287,32 @@ interface PolicyFilter {
146
287
  interface ValidationResult {
147
288
  valid: boolean;
148
289
  }
149
- interface FetchOptions {
290
+ /**
291
+ * Options for a single call, passed to `.fetch()`.
292
+ *
293
+ * Note that `await`ing a builder directly (`await wh.from("t").select("*")`)
294
+ * takes no options — use the explicit `.fetch({ … })` form for those.
295
+ */
296
+ interface RequestOptions {
150
297
  signal?: AbortSignal;
151
298
  limit?: number;
152
299
  }
300
+ /**
301
+ * Options for a single `PipeRef.fetch()` call.
302
+ *
303
+ * `limit` is declared `never` rather than simply left out. Omitting it would
304
+ * still admit a `RequestOptions` value that carries one — excess-property
305
+ * checking only rejects fresh object literals, so a variable would pass and the
306
+ * limit would be silently dropped, which is the whole defect this prevents.
307
+ *
308
+ * A pipe's row cap belongs in its SQL as a `{{limit}}` parameter, supplied via
309
+ * `wh.pipe(name, { limit })`.
310
+ */
311
+ interface PipeRequestOptions {
312
+ signal?: AbortSignal;
313
+ /** Not supported on pipes — pass `limit` as a pipe parameter instead. */
314
+ limit?: never;
315
+ }
153
316
  interface StreamOptions {
154
317
  since?: string;
155
318
  signal?: AbortSignal;
@@ -160,6 +323,9 @@ interface HttpContext {
160
323
  auth?: () => Promise<string> | string;
161
324
  options: {
162
325
  maxRetries: number;
326
+ fetch?: FetchLike;
327
+ headers?: Record<string, string>;
328
+ fetchOptions?: RequestInit;
163
329
  };
164
330
  }
165
331
 
@@ -236,8 +402,15 @@ declare class PipeRef<Row = Record<string, unknown>> implements PromiseLike<Resu
236
402
  private readonly _params?;
237
403
  private readonly _createStream;
238
404
  constructor(ctx: HttpContext, name: string, params: Record<string, unknown> | undefined, createStream: CreateStreamFn$2<Row>);
239
- /** Execute the pipe and return results. */
240
- fetch(opts?: FetchOptions): Promise<Result<Row[]>>;
405
+ /**
406
+ * Execute the pipe and return results.
407
+ *
408
+ * Takes only `signal` — deliberately narrower than the `RequestOptions` the
409
+ * query builder accepts. The pipes endpoint binds the body as the pipe's
410
+ * parameters, so there is no row cap to forward; give the pipe a `{{limit}}`
411
+ * parameter in its SQL and pass it via `wh.pipe(name, { limit })`.
412
+ */
413
+ fetch(opts?: PipeRequestOptions): Promise<Result<Row[]>>;
241
414
  /** Subscribe to live events from the pipe's underlying query. */
242
415
  stream(opts?: StreamOptions): StreamController<Row>;
243
416
  then<TResult1 = Result<Row[]>, TResult2 = never>(onfulfilled?: ((value: Result<Row[]>) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
@@ -339,6 +512,7 @@ declare class LiveQuery<T = Record<string, unknown>> {
339
512
  interface QueryState {
340
513
  table: string;
341
514
  columns: string[];
515
+ selectAll?: boolean;
342
516
  aggregations: Aggregation[];
343
517
  filters: QueryFilter[];
344
518
  groupBy: string[];
@@ -361,6 +535,13 @@ declare class QueryBuilder<Row = Record<string, unknown>> implements PromiseLike
361
535
  private readonly _createStream;
362
536
  constructor(ctx: HttpContext, state: QueryState, createStream: CreateStreamFn$1<Row>);
363
537
  select(...columns: string[]): QueryBuilder<Row>;
538
+ /**
539
+ * Select every column the caller's role is allowed to read (the all-columns
540
+ * wildcard). Use this instead of `.select(...)` when you want a full-row read;
541
+ * a bare `.fetch()` with no `.select()` does this implicitly. Mutually
542
+ * exclusive with `.select(...)`.
543
+ */
544
+ selectAll(): QueryBuilder<Row>;
364
545
  where(column: string, op: FilterOp, value: unknown): QueryBuilder<Row>;
365
546
  count(column?: string, alias?: string): QueryBuilder<Row>;
366
547
  sum(column: string, alias?: string): QueryBuilder<Row>;
@@ -374,9 +555,9 @@ declare class QueryBuilder<Row = Record<string, unknown>> implements PromiseLike
374
555
  limit(n: number): QueryBuilder<Row>;
375
556
  timeRange(column: string, since: string, until?: string): QueryBuilder<Row>;
376
557
  cacheTTL(seconds: number): QueryBuilder<Row>;
377
- /** Default row limit when none is specified. Matches backend DefaultMaxRows. */
558
+ /** Default row limit when none is specified — deliberately tighter than the backend's DefaultMaxRows (10000) safety cap. */
378
559
  static readonly DEFAULT_LIMIT = 1000;
379
- fetch(opts?: FetchOptions): Promise<Result<Row[]>>;
560
+ fetch(opts?: RequestOptions): Promise<Result<Row[]>>;
380
561
  stream(opts?: StreamOptions): StreamController<Row>;
381
562
  /**
382
563
  * Start a live query: fetches historical data, then streams live updates.
@@ -396,6 +577,12 @@ declare class QueryBuilder<Row = Record<string, unknown>> implements PromiseLike
396
577
  }
397
578
 
398
579
  type CreateStreamFn<Row> = (table: string, opts?: StreamOptions) => StreamController<Row>;
580
+ /**
581
+ * Accepted sources for {@link TableRef.insertNDJSON}: a string, raw bytes, a
582
+ * Blob/File (browser file inputs), or a byte stream. Non-string sources are
583
+ * read fully before sending.
584
+ */
585
+ type NDJSONSource = string | Uint8Array | Blob | ReadableStream<Uint8Array>;
399
586
  /**
400
587
  * Reference to a table. NOT thenable — safe to pass around without triggering requests.
401
588
  * Use `.fetch()`, `.select()`, `.insert()`, `.schema()`, or `.stream()` to act on it.
@@ -406,13 +593,51 @@ declare class TableRef<Row = Record<string, unknown>> {
406
593
  private readonly _createStream;
407
594
  constructor(ctx: HttpContext, table: string, createStream: CreateStreamFn<Row>);
408
595
  /** SELECT * shortcut — fetches rows with optional pagination. */
409
- fetch(opts?: FetchOptions): Promise<Result<Row[]>>;
596
+ fetch(opts?: RequestOptions): Promise<Result<Row[]>>;
410
597
  /** Start building a typed query. Returns an immutable, PromiseLike QueryBuilder. */
411
598
  select(...columns: string[]): QueryBuilder<Row>;
412
- /** Insert one or more rows into this table. */
599
+ /**
600
+ * Start a query that selects every column the caller's role is allowed to read
601
+ * (the all-columns wildcard). Use instead of `.select(...)` for an explicit
602
+ * full-row read; `.fetch()` does this implicitly.
603
+ */
604
+ selectAll(): QueryBuilder<Row>;
605
+ /**
606
+ * Insert one or more rows into this table.
607
+ *
608
+ * A single object is sent as a JSON `POST /v1/ingest`. An **array** is
609
+ * serialized to NDJSON (one record per line) and sent as a single
610
+ * `application/x-ndjson` request: a bad record no longer fails or hides the
611
+ * rest of the batch — per-record outcomes come back in the result
612
+ * (`failed` / `results`), and `ok` is true only when every record succeeded.
613
+ *
614
+ * The array path sends one request regardless of size; bounded-concurrency
615
+ * chunking of very large arrays is tracked separately (#196). For NDJSON you
616
+ * already have (a file or stream), use {@link insertNDJSON}.
617
+ */
413
618
  insert(data: Partial<Row> | Partial<Row>[], opts?: {
414
619
  signal?: AbortSignal;
415
620
  }): Promise<Result<InsertResult>>;
621
+ /**
622
+ * Insert pre-formatted NDJSON (newline-delimited JSON, one record per line)
623
+ * from a string, raw bytes, a Blob/File, or a byte stream — e.g. a `.ndjson`
624
+ * file or a stream produced by another system. For in-memory rows, prefer
625
+ * {@link insert}.
626
+ *
627
+ * Non-string sources are read fully into memory before sending (the server
628
+ * streams the parse). Returns the same per-record batch summary as an array
629
+ * `insert`.
630
+ */
631
+ insertNDJSON(source: NDJSONSource, opts?: {
632
+ signal?: AbortSignal;
633
+ }): Promise<Result<InsertResult>>;
634
+ /**
635
+ * @internal Send an NDJSON body and map the server's batch response onto an
636
+ * {@link InsertResult}. A transport / whole-request failure surfaces as the
637
+ * Result error arm; a processed batch (even with rejected records) surfaces
638
+ * as the success arm with `ok = failed === 0`.
639
+ */
640
+ private _sendNDJSON;
416
641
  /** Fetch the schema for this table. */
417
642
  schema(opts?: {
418
643
  signal?: AbortSignal;
@@ -458,4 +683,4 @@ declare class WaveHouseClient<DB extends Database = Database> {
458
683
  /** Create a new WaveHouse client instance. */
459
684
  declare function createClient<DB extends Database = Database>(config: ClientConfig<DB>): WaveHouseClient<DB>;
460
685
 
461
- export { type Aggregation, type ClientConfig, type ClientOptions, type Column, DLQNamespace, type DLQStats, type Database, type FetchOptions, type FilterOp, type InsertResult, LiveQuery, type OrderClause, type ParamDef, type Pipe, PipeRef, PipesNamespace, type Policy, type PolicyFilter, PolicyNamespace, QueryBuilder, type QueryFilter, type Result, type RolePermissions, SchemaNamespace, type Schemas, StreamController, type StreamEvent, type StreamOptions, type StreamStatus, type StreamSubscriber, type StructuredQuery, SysNamespace, type TablePolicy, TableRef, type TableSchema, type TimeRange, type ValidationResult, WaveHouseClient, type WaveHouseError, createClient };
686
+ export { type Aggregation, type ClientConfig, type ClientOptions, type Column, DLQNamespace, type DLQStats, type Database, type FetchLike, type FilterOp, type InsertRecordResult, type InsertResult, LiveQuery, type NDJSONSource, type OrderClause, type ParamDef, type Pipe, PipeRef, type PipeRequestOptions, PipesNamespace, type Policy, type PolicyFilter, PolicyNamespace, QueryBuilder, type QueryFilter, type RequestOptions, type Result, type RolePermissions, SchemaNamespace, type Schemas, StreamController, type StreamEvent, type StreamOptions, type StreamStatus, type StreamSubscriber, type StructuredQuery, SysNamespace, type TablePolicy, TableRef, type TableSchema, type TimeRange, type ValidationResult, WaveHouseClient, type WaveHouseError, createClient };